LeetCode 1. Two Sum

問題

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

分析

如果直接用兩個for循環來做的話,非常直接和簡單,但是速度很慢。時間複雜度O(n^2),空間複雜度O(1)。
所以使用hash table來做。時間複雜度O(n),空間複雜度O(n)。
C++標準庫中沒有hash,但是可以使用 unordered_map 來實現,它內部就是一個hash表。
格式:unordered_map

代碼

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int i,j;
        vector<int> result;
        for(i=0; i<nums.size(); i++)
            for(j=i+1; j<nums.size(); j++)
                if(target == nums[i] + nums[j]) 
                {
                    result.push_back(i);
                    result.push_back(j);
                    return result;
                    //上面三行還可以簡化爲: return {i,j};
                }
         return result;           
    }

    //for循環做實在太low,使用哈希表。C++標準庫中沒有hash,
    //但是可以使用unordered_map來實現,它內部就是一個hash表。
    vector<int> twoSum(vector<int> &nums, int target)
    {
    //unordered_map<type key, type value>,這裏數組值 作key,下標作 value。
      unordered_map<int, int> hash;
      vector<int> result;
      for (int i = 0; i < nums.size(); i++)
      {
          int numberToFind = target - nums[i];
          //if numberToFind is found in map, return them
          if (hash.find(numberToFind) != hash.end()) 
          {/*
            result.push_back(hash[numberToFind] );
            result.push_back(i);    //注意先後順序,找到說明之前放進去的,所以在前面。      
            return result; */
            //上面三行還可以簡化爲:
            return {(*(hash.find(numberToFind))).second, i};
          }
          //if number was not found. Put it in the map.
          hash[nums[i]] = i;
       }
       return result;
    }
};

總結

發佈了31 篇原創文章 · 獲贊 24 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章