码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 1 two sum 难度:0

时间:2015-08-25 19:16:49      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/two-sum/

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> index(2,0);
        vector<int> n2;
        int numsSize = nums.size();
        int f = -1;
        for(int i = 0;i < numsSize;i++){
            n2.push_back(nums[i]);
            if(nums[i] == target/2 && target%2 ==0){
                if(f != -1){
                    index[0] = min(f,i + 1);
                    index[1] = max(f,i + 1);
                    return index;
                }
                else f = i + 1;
            }
        }
        sort(nums.begin(),nums.end());
        for(int i = 0;i < numsSize;i++){
            int j = lower_bound(nums.begin(),nums.end(),target - nums[i]) - nums.begin();
            int a,b;
            if(nums[i] + nums[j] == target && j < numsSize){
                for(int k = 0;k < numsSize;k++){
                    if(nums[i] == n2[k]) a = k + 1;
                    if(nums[j] == n2[k]) b = k + 1;
                }
                index[0] = min(a,b);
                index[1] = max(a,b);
            }
        }
        return index;
    }
};

  

 

Leetcode 1 two sum 难度:0

标签:

原文地址:http://www.cnblogs.com/xuesu/p/4758252.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!