[LeetCode] Two Sum系列

LeetCode 1. Two Sum

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

分析:

此题是这个系列中AC率最低的一道了,楼主并没有想出什么好办法,当你没有好办法的时候,总是想到暴搜,这样不好,嘿嘿。暴搜就不用多说了,复杂度为O(n2)。以下给出一种O(n)的解法,利用unordered_map的哈希存储优势。

代码:

class Solution {
    public:
    vector<int> twoSum(vector<int>& nums, int target) {
         vector<int> results(2,-1);
         unordered_map<int,int> marks;
         int len = nums.size();
         for(int i=0; i < len; i++){
             if(marks.find(target-nums[i])!=marks.end()){
                  results[0] = marks[target-nums[i]] + 1;
                  results[1] = i + 1;
                  break;
             } else 
             marks[nums[i]] = i;
         }
         return results;
    }       
}   

 

LeetCode 167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, 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

分析:

有序的这道题比较自然的能想到单趟快排的思想,复杂度为O(n)。在数组的两端分别设一个指针,如果两数之和大于target,则左移尾指针;小于target则右移头指针,直到遇到一对和等于target的整数。

代码:

class Solution{
public:
    vector<int> TwoSum(vector<int> nums, int target){
        vector<int> ret(2,-1);
        int begin=0;
        int end = nums.size()-1;
        while(begin<end){
             int tempSum = nums[begin]+nums[end];
             if(tempSum > target)
                  end--;
             else if(tempSum < target)
                  begin++;
             else
                  break;  
        }
        ret[0]=begin+1;
        ret[1]=end+1;
        return ret;
    }  
}    
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ret={-1,-1};
        int begin=0;
        int end=nums.length-1;    
        while(begin<end){
            int tempSum = nums[begin]+nums[end];
            if(tempSum>target)
                end--;
            else if(tempSum<target)
                begin++;
            else
                break;
        }
        ret[0]=begin+1;
        ret[1]=end+1;
        return ret;  
    }
}
View Code

 

延伸思考:

试想想这道题的变种, 如果去掉这个假设(有且仅有一对数满足要求),也就是说可能一对符合要求的都没有,也有可能有多对,要求全部输出。

 

posted @ 2015-09-22 13:12  eaglet-weixi  阅读(184)  评论(0编辑  收藏  举报