leetcode 第一題 Two Sum


title: Leet Code TwoSum
date: 2017-07-08 23:18:54
tags:
- LeetCode
- 算法
categories: 算法


題目:

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

第一反應(yīng)可以把nums循環(huán)兩次,用n^2的時間復(fù)雜度

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
       int n = numbers.size();
        vector<int> ans;
        for (int i = 0; i < n-1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (numbers[i] + numbers[j] == target) {
                    ans.push_back(i);
                    ans.push_back(j);
                    return ans;
                }
            }
        }
        return ans;
    }
};

后來想到可以把每個數(shù)字放到Map里,總的時間復(fù)雜度可以到n。

class Solution{
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        map<int, int> mymap;
        int n = numbers.size();
        vector<int> ans;
        for(int i=0;i<n;i++){
            int t = target - numbers[i];
            if(mymap.count(t) > 0){
                ans.push_back(mymap[t]);
                ans.push_back(i);
                return ans;
            }else{
                mymap[numbers[i]] = i;
            }
        }
        return ans;
    }
};

上面程序的運(yùn)行時間是9ms,打敗了54.67% 。

后來看了前排6ms的代碼,發(fā)現(xiàn)只是把map換成了unorder_map,因?yàn)閙ap是紅黑樹實(shí)現(xiàn)的,會根據(jù)鍵的大小排序,查找的時間復(fù)雜度是n,而unorder_map沒有排序,是hash實(shí)現(xiàn)的,查找的時間復(fù)雜度是常數(shù)級,因此會更快。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 一、題目說明 Given an array of integers, return indices of the ...
    Diffey閱讀 5,099評論 4 3
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,771評論 0 33
  • 題目 題目的意思是在一個整形數(shù)組中查找連個數(shù)字,使其和等于給定的目標(biāo)。并返回給出這兩個數(shù)出現(xiàn)的位置。 分析 初讀題...
    baixiaoshuai閱讀 515評論 0 0
  • HTML筆記--表單標(biāo)簽 標(biāo)簽(空格分隔): HTML 表單標(biāo)簽(****最重要的一個標(biāo)簽*****) 可以用來實(shí)...
    醒著的碼者閱讀 200評論 0 0
  • 春 蘋果樹上淺綠色, 人們盼望它結(jié)果。 夏 蘋果樹上綠油油, 人們在樹下乘涼。 秋 蘋果樹上紅彤彤, 人們采下蘋果...
    EEEEElectric閱讀 2,116評論 1 1