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; } }
延伸思考:
試想一想這道題的變種, 若是去掉這個假設(有且僅有一對數知足要求),也就是說可能一對符合要求的都沒有,也有可能有多對,要求所有輸出。