1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路:先將輸入的array排序,再用前後夾擊的方式,取得答案。

如果 兩數相加 < 目標,代表左邊的index要往下一個移動。

如果 兩數相加 > 目標,代表右邊的index要往前一個移動。

typedef struct Number{
    int index;
    int value;
}Number;

bool compare(const Number & num1,const Number & num2){
    return num1.value < num2.value;
}


class Solution {
public:

    vector<int> twoSum(vector<int>& nums, int target)
    {
<span style="white-space:pre">	</span>// 因為排序完 index就會錯亂,先用Number記起來
        vector<Number> my_nums;
        Number number;
        for(int index = 0; index < nums.size(); index++) {
            number.value = nums[index];
            number.index = index;
            my_nums.push_back(number);
        }
        
<span style="white-space:pre">	</span>//排序
        sort(my_nums.begin(), my_nums.end(), compare);
        
        vector<int> result;
        int begin = 0;
        int tail = my_nums.size() - 1;
        
<span style="white-space:pre">	</span>//開始夾擊
        for (int index = 0; index < nums.size(); index++) {

            if(my_nums[begin].value + my_nums[tail].value < target) {
                begin++;
                continue;
            }
            
            if(my_nums[begin].value + my_nums[tail].value > target) {
                tail--;
                continue;
            }

<pre name="code" class="cpp" style="color: rgb(51, 51, 51); font-size: 14px;">            if(my_nums[begin].value + my_nums[tail].value == target) {
                if (my_nums[begin].index > my_nums[tail].index) {
                    result.push_back(my_nums[tail].index);
                    result.push_back(my_nums[begin].index);
                } else {
                    result.push_back(my_nums[begin].index);
                    result.push_back(my_nums[tail].index);   
                }
                return result;
            }
} return result; }};

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值