[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.less

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.ide

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

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2spa

分析:指针

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

代码:blog

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 sortedci

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.get

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

 

延伸思考:

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

相关文章
相关标签/搜索