【LeetCode】1 Two Sum

题目链接

Two Sum

分析

给出一个数组,找出俩个数,二者之和为指定的target。
注意点:

(1)返回的是二者的下标;
(2)数组元素有可能是负数

采用结构体来标记一个节点的值和下标,将节点按照值的大小排序,而后采用二分查找。

代码

    struct node{
        node(int _val, int _pos){
            val = _val;
            pos = _pos;
        }
        int val, pos;
    };
    bool cmp(node a, node b){
        if(a.val!=b.val){
            return a.val < b.val;
        }else{
            return a.pos < b.pos;
        }
    }

    int binaryFind(vector<node> &vec, int left, int right, int s){
        int mid, midVal, notFound=-1;
        while(left <= right){
            mid = (left+right)/2;
            midVal = vec[mid].val;
            if(midVal < s){
                left = mid + 1;
            }else if(midVal > s){
                right = mid -1;
            }else{
                return mid;
            }       
        }   
        return notFound;
    }

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
           int i, len;
           vector<node> vec;
           for(i=0; i<nums.size(); i++){
                node t(nums[i],i+1);
                vec.push_back(t);
           }
           sort(vec.begin(), vec.end(), cmp);
           int posa, posb;
           for(i=0; i<vec.size(); i++){
                posa = vec[i].pos;
                posb = binaryFind(vec,i+1, vec.size(), target-vec[i].val);
                if(posb!=-1){
                    posb = vec[posb].pos;
                    break;
                }
           }
           if(posa>posb){
               int t = posa;
               posa = posb;
               posb = t;
           }
           vector<int> ans;
           ans.push_back(posa);
           ans.push_back(posb);     
           return ans;  
        }    
    };

你可能感兴趣的:(LeetCode,二分查找)