1. 程式人生 > >Leetcode_Array --167. Two Sum II

Leetcode_Array --167. Two Sum II

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. 這個方程應該返回相加等於目標數的兩個數的索引,這裡的索引1必須小於索引2

Note: 1、Your returned answers (both index1 and index2) are not zero-based. 2、You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

Solution: 演算法與之前的Two Sum相似,只是在if判斷的時候多添加了一個索引判斷條件

Python

class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashtable = {}
        for i in range(len(numbers)):
            left = target - numbers[i]
            if numbers[i] in hashtable and i>hashtable[numbers[i]]:
                return [hashtable[numbers[i]]+1,i+1]
            else:
                hashtable[left] = i
C++

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int start = 0;   #利用雙指標,一個指向頭部,一個指向尾部
        int end = numbers.size()-1;
        while(start<end){
            if (numbers[start]+numbers[end] == target){   #如果和數相等,直接返回index
                break;
            }
            if (numbers[start]+numbers[end]<target){   #如果和數小於target,則指向頭部指標向後移動,因為陣列升序排列,和數會越來越大;否則指向尾部的指標向前移動,減小和數。
                start++ ;
            }
            else{
                end--;
            }
        }
        return {start+1,end+1};
        
    }
};
--------------------------------------------------------------
超時程式碼,思路和Python的是一樣的
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        unordered_map<int,int> Map;
        for (int i=1;i<numbers.size();i++){
            int left = target - numbers[i];
            Map[left] = i;
            if (Map.count(numbers[i]) != 0  && i>Map[numbers[i]]){
                return {Map[numbers[i]],i};
            }
            else{
                Map[left] = i;
            }
        }
        
    }
};