1. 程式人生 > >Leetcode---1.Two Sum

Leetcode---1.Two Sum

Description:

  • Given an array of integers, return indices of the two numbers such that they add up to a specific target.
    Example:
    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

  • 分析:
    給定一個數組nums和target,求陣列中的兩個數使得之和為target,並返回其索引。

方法一:暴力列舉法
思路很簡單,將所有可能的組合進行判斷,返回滿足條件組合的索引,其時間複雜度為O(n^n)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ret(2,-1);
        int size=nums.size();
        for(int i=0;i<size-1;i++){
            for(int j=i+1;j<size;j++){
                int sum=nums[i]+nums[j];
                if
(sum==target){ ret[0]=i; ret[1]=j; } } } return ret; } };

方法二:雜湊表
將陣列轉換為雜湊表,通過查詢target-nums[i]來確定組合。注意這裡將陣列的元素作為key,索引作為value,因為我們想要得到的陣列索引。這樣只需要遍歷一次陣列,演算法的時間複雜度為O(n)

class Solution {
public:
    vector<int
>
twoSum(vector<int>& nums, int target) { vector<int> ret(2,-1); //將陣列的元素作為Key,索引作為value unordered_map<int,int> m; int size=nums.size(); //將整個陣列轉換為雜湊表 for(int i=0;i<size;i++){ m[nums[i]]=i; } //查詢target-nums[s]是否存在 for(int i=0;i<size;i++){ const int gap=target-nums[i]; if(m.find(gap)!=m.end()&&m[gap]>i){ ret[0]=i; ret[1]=m[gap]; break; } } return ret; } };