程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> leetcode_01_Two sum

leetcode_01_Two sum

編輯:C++入門知識

leetcode_01_Two sum


 

 

Two sum

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 用兩個指標start和end從數組兩頭往中間走,如果兩個當前數字的和比目標數字小,那麼start往後走一位。如果兩個當前
數字的和比目標數字大,那麼end往前走一位。如果兩個當前數字的和等於目標數,那麼我們就得到了start和end的指標。
3 找到start和end所對應數字在原始數組中的位置
*/

class Solution {
public:
    vector twoSum(vector &numbers, int target) {
        vector result;
        vector temp = numbers;
        sort(temp.begin() , temp.end());
        int start = 0 , end = temp.size()-1;
        while(temp[start] + temp[end] != target)
        {
            if(temp[start] + temp[end] < target)
                start++;
            else
                end--;
        }
        int i = 0;
        while(numbers[i] != temp[start])
        {
            i++;
        }
        result.push_back(i+1);
        

        int j = numbers.size()-1;
        while(numbers[j] != temp[end])
        {
            j--;
        }
		/*可能輸出的下標位置會變成倒序
			Input:	[5,75,25], 100
			Output:	3, 2
			Expected:	2, 3
		*/
        if(result[0] <= j+1)
            result.push_back(j+1);
        else
            result.insert(result.begin() , j+1);//插入到begin()之前
        

        return result;
    }
};

/*方法二:Map
為<值,下標>,map中保存的是已經掃描過的number。
這是一種很直觀很自然的做法:
對於numbers[i],如果map中存在K=target-numbers[i],則要求的解為V(K=target-numbers對應的)和i;
如果不存在,則向map中添加。
*/

class Solution {
public:
    vector twoSum(vector &numbers, int target) {
        int i, sum;
        vector results;
        map hmap;
        for(i=0; i(numbers[i], i));
            }
            if(hmap.count(target-numbers[i]))
			{
                int n=hmap[target-numbers[i]];
                if(n

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved