Two Sum

本文介绍了一种解决两数之和问题的算法实现。给定整数数组及目标值,寻找两个数使它们的和等于目标值,并返回这两个数的索引。文章通过排序与双指针技巧实现了高效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

今天试图做出来那道最长回文字符串,结果很不开心,就把这道简单点的题目拿来泻愤,不过编程还是要理智,不然会更不开心。。。

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
    	vector<int> xxx(numbers);//因为要返回索引,就用一个备份来排序
    	int len = numbers.size();
        sort(xxx.begin(), xxx.end());
        int i = 0, j = len - 1;
        while(i < j)
        {
        	if(xxx[i] + xxx[j] > target)//此时j减小,即xxx[j]减小
        	{
        		j--;
        	}
        	else if(xxx[i] + xxx[j] < target)//此时i增大,即xxx[i]增大
        	{
        		i++;
        	}
        	else//相等了!!!
        	{
        		break;
        	}
        }
        vector<int> x;
        if(i < j)
        {
        	for(int k = 0; k < len; k++)
        	{
        		if(i >= 0 && numbers[k] == xxx[i])
        		{
        			x.push_back(k + 1);
        			i = -1;
        		}
        		else if(j >= 0 && numbers[k] == xxx[j])//如果没有这个else,当xxx[i] == xxx[j]时就纠结了
        		{
        			x.push_back(k + 1);
        			j = -1;
        		}
        	}
        }
        return x;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值