关闭

【Leetcode】Two Sum

标签: 元素相加leetcode
610人阅读 评论(0) 收藏 举报
分类:

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> result;
        if(numbers.empty())
            return result;
        vector<int> backup(numbers);
        sort(numbers.begin(),numbers.end());
        getIndex(result,numbers,target);
        int index1,index2;
        bool finding=true;
        for(int i=0;i<backup.size();i++)
        {
            if(backup[i]==result[0]&&finding)
            {
                index1=i+1;
                finding=false;
                continue;
            }
            if(backup[i]==result[1])
                index2=i+1;
        }
        result.clear();
        result.push_back(index1);
        result.push_back(index2);
        sort(result.begin(),result.end());
        return result;
    }
    
    void getIndex(vector<int> &result,vector<int> &numbers,int target)
    {
        for(int i=numbers.size()-1;i>=0;i--)
        {
            if(target>numbers[i])
            {
                int index2=numbers[i];
                bool index1=find(numbers,target-numbers[i],0,i-1);
                if(index1)
                {
                    result.push_back(target-index2);
                    result.push_back(index2);
                    return;
                }
                else
                    continue;
            }
        }
    }
    
    bool find(vector<int> &numbers,int target,int start,int end)
    {
        if(end<start)
            return false;
        int medium=(start+end)>>1;
        if(target==numbers[medium])
            return true;
        else if(target<numbers[medium])
            return find(numbers,target,start,medium-1);
        else
            return find(numbers,target,medium+1,end);
    }
    
};

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:58672次
    • 积分:1269
    • 等级:
    • 排名:千里之外
    • 原创:66篇
    • 转载:14篇
    • 译文:0篇
    • 评论:2条
    博客专栏