1. 程式人生 > >leetcode 1: 找出兩個數相加等於給定數 two sum

leetcode 1: 找出兩個數相加等於給定數 two sum

問題描述

對於一個給定的陣列,找出2個數,它們滿足2個數的和等於一個特定的數,返回這兩個數的索引。(從1開始)
Given an array of integers, 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. 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

解決方案

1.思路分析:

我們將求2個數的索引轉換成在陣列中搜索(target-nums[i])的位置;

直觀想,兩層遍歷,固定一個元素,迴圈右移另一個元素,逐個測試,時間複雜度O(n2),而O(n2)一般不能接受,因此需要考慮改進演算法:
想法則是降低到O(nlgn),最理想則是O(n)

2.測試樣例:

正數、負數、0

3.特殊情況:

陣列不足2個數、兩數相加溢位、沒有匹配的情況

4.實現

4.1 兩層遍歷的實現:O(n2)

#include <iostream>
using namespace std;
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    returnSize = NULL;
    if (numsSize < 2)
        return returnSize;
    int i = -1;
    int j;
    while
(++i < numsSize-1) { if (nums[i] >= target) continue; j = i; while (++j < numsSize) { compare_times++; if (nums[i] + nums[j] == target) break; } if (j == numsSize) continue; else break; } if (i != numsSize-1) { returnSize = new int [2]; returnSize[0] = i+1; returnSize[1] = j+1; } return returnSize; } int main() { int nums[] = {-1, 0, 9, 5, 7, 11, 15, 20}; int target = 9; int *index = NULL; index = twoSum(nums, sizeof(nums)/sizeof(nums[0]), target, index); if(index != NULL) cout<<"index1 = "<<index[0]<<", index2 = "<<index[1]<<endl; }

提交到leetcode 返回Time Limit Exceeded,不滿足時間要求。

4.2 排序實現 O(nlgn)

首先將陣列進行快速排序或者插入到二叉搜尋樹中,二分查詢,當固定一個元素nums[i],在陣列中查詢target - nums[i],此時查詢時間降低到O(lgn),總消耗即為O(nlgn)

4.3 線性實現-Hash表 O(n)

我們知道對元素的搜尋最快則是O(1),即直接索引到,聯想只能是Hash表或者是關鍵字索引。關鍵字索引(從最小到最大)會佔用額外的記憶體空間。
由於C++有現成的hash map,所以直接採用c++。
另外我們要求的是元素的索引,即Hash表的關鍵字,所以我們把陣列元素作為Hash表的關鍵字,而把陣列元素的索引作為Hash表的元素值。

class Solution
{
public:
    vector<int> twoSum(const vector<int> &nums, int target) {
        vector<int> results;
        if (nums.size() < 2) {
            return results;
        }
        map <int , int> hmap;
        //插入到hash map
        for (int i = 0; i < nums.size(); i++) {
            hmap.insert(pair <int, int> (nums[i], i) ); //元素值做關鍵值
        }
        int j;
        for (int i = 0; i < nums.size(); i++) {
            //hmap.count(x):x在hash map中出現的次數
            if (hmap.count(target - nums[i])) {
                j = hmap[(target - nums[i])];
                if (j < i) {
                    results.push_back(j+1);
                    results.push_back(i+1);
                }
            }
        }
        return results;
    }
};

測試

int main()
{
    int nums[] = {0,-3, 2, 7, 11, 15, 20};
    vector<int> nums_v(nums, nums+7);
    int target = 9;
    while (1) {
        class Solution sol;
        vector<int> results = sol.twoSum(nums_v, target);
        if(results.size())
            cout<<"index1 = "<<results[0]<<", index2 = "<<results[1]<<endl;
    }
    getchar();
}

相關推薦

leetcode 1: 個數相加等於給定 two sum

問題描述 對於一個給定的陣列,找出2個數,它們滿足2個數的和等於一個特定的數,返回這兩個數的索引。(從1開始) Given an array of integers, find two numbers such that they add up to a s

陣列中相加等於個數

public static void main(String[] args) throws IOException { int[] a={4,5,3,2,7,9,1}; findS

Java演算法給定一個整數陣列,其中個數相加等於目標值

給定一個整數陣列,找出其中兩個數相加等於目標值  例如:給定陣列及目標值 nums = [2,7,11,15] ,target = 9  因為nums[0] + nums[1] = 2 + 7 = 9  返回[0,1] /** * 使用輔助空間(使用雜湊表

1.無序陣列中個數使其和等於給定

碰到這種類似題目可以根據條件不同寫出不同時間複雜度的程式碼: 1.最暴力的遍歷,時間複雜度為O(n^2) 2.一般情況下先排序,再從兩邊向中間搜尋結果,時間複雜度為O(nlogn + n) int i = 0, j = numbers.size() - 1; while

之和:給定一個整數陣列,其中個數相加等於目標值

題目:給定一個整數數列,找出其中和為特定值的那兩個數。 你可以假設每個輸入都只會有一種答案,同樣的元素不能被重用。 有三種思路: 第一個思路:遍歷陣列i從第一個數開始,j從(i+1)開

【死磕演算法之1Leetcode】——個有序陣列的中位數【Median of Two Sorted Arrays】O(log(m+n))

Median of Two Sorted Arrays 題目難度:hard 題目要求: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two s

個數組中不相同的元素

不同的 out 優化 ont 相同 array ted str args 找出兩個數組中不相同的元素,網上貼出的代碼基本如下: /** * 找出兩個數組中不同的元素 */ public class Test3 { public static Set<In

個數組相同的元素,並且對應的個數一樣

contains println .get system void con main cnblogs highlight /** * 找出兩個數組相同的元素,並且對應的個數一樣 * @param args */ public static void

k個數相加得n的所有組合

gpo caller define 所有 ack nbsp not != array Find all possible combinations of k positive numbers that add up to a number n,each combinatio

個數組中都有,並且重復次數最多的元素

var In IT 兩個 code TE total urn des var itemA = [1, 2, 3, 3] var itemB = [3, 3, 2] var crossArr = []; var countArr = []; itemA.forEach((e

java中請給例子程序:個數的最大公約數和最小公倍數

strong big ont com 約數 計算 www main .html 9.2 找出12和8的最大公約數和最小公倍數。 (視頻下載) (全部書籍) public class Test { public static void main(String[]

位運算---不用任何比較判斷個數中的最大值

【題目】   給定兩個32位整數a和b,返回a和b中較大的一個。要求不能使用比較判斷。 【基本思路】  方法一。得到a - b的符號就可以知道a和b哪一個大了。具體過程參照如下程式碼: int getMax1(int a, int b) {

個數相加等於目標的問題

問題闡述   遇到了一個演算法問題,話說三個數相加等於目標數,並且時間複雜度為最小。例如{1,3,5,9,6,8,7,2,4},其中三個數相加等於15,找出這些數。   思考:對於這個問題,時間複雜度要求最小,那麼只有一層迴圈來做,找到三個數的和是目標數,需要先排序,然後通過三個指標來進行移動,比如說i,

快速個數組中的個數字,讓這個數字之和等於一個給定的值

http 知識 繼續 進一步 repl 有一個 tails 窮舉 too 我覺得寫得很清晰,希望沒有侵犯作者的著作權,原文地址http://blog.csdn.net/hackbuteer1/article/details/6699642 快速找出一個數組中的兩個數字,讓這

題目:一個數如果恰好等於它的因子之和,這個數就稱為"完"。例如6=1+2+3.程式設計1000以內的所有完

兩個易錯點:1.sum應該在每次內迴圈結束之後進行初始化。2.對因子之和與數本身的判斷應該在內迴圈結束後。  public class Test9 { public static void main(String[] args) { int sum,i,j; for(i

ACMNO.11 一個數如果恰好等於它的因子之和,這個數就稱為"完"。 例如,6的因子為1、2、3,而6=1+2+3,因此6是"完"。 程式設計序N之內的所有完,並按下面格式輸出其因子

寫在前面,心得感悟~ 程式碼越來越有難度! 這個ACM題,我除錯了 將近50次~ 一個小時! 真的是,年紀輕輕的搞什麼ACM呀! 關於題的解決思路放在下面再寫吧! 題目描述 一個數如果恰好等於它的因子之和,這個數就稱為"完數"。 例如,6的因子為1、2、3,而6=1+2+

php 個數組中的個數字,讓這個數字之和等於一個給定的值

有關於php的有好幾種思路,很多部落格都有我就不一一介紹了,只是貼程式碼僅供參考。 問題:給一個一維陣列,不確定具體有多少元素,例如$arr = [1,2,3,4,3,2,1],讓他們任意兩數字相加的和等於一個給定的值,比如說 5 ,可能有好幾個兩個數相加都是5,但只是取最

程式設計師面試題:快速個數組中的個數字,讓這個數字之和等於一個給定的值

能否快速找出一個數組中的兩個數字,讓這兩個數字之和等於一個給定的值,為了簡化起見,我們假設這個陣列中肯定存在至少一組符合要求的解。 假如有如下的兩個陣列,如圖所示: 5,6,1,4,7,9,8 給定Sum= 10 1,5,6,7,8,9 給定Sum=

go語言實現--個數組中的個數,這個數之和等於一個給定的值

前幾天面試的時候問了我一道演算法題,題目是 :快速找出一個數組中的兩個數字,讓這兩個數字之和等於一個給定的值所以把它記錄下來解法一:窮舉,從陣列中任意取出兩個數字,計算兩者之和是否為給定的數字,時間複雜

Two Sum 陣列內個數相加和為n的下標

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