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

leetcode---------------Two Sum

編輯:C++入門知識

leetcode---------------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

題目意思是:給定一個數組,給一個數target,在數組找到兩個數的和為target,找出這個兩個數的位置,其下標索引從1開始算起。

思路:

方法一:暴利求,兩個for循環遍歷,找到退出,復雜度O(n2)

方法二::hash 用一個哈希表,存儲每個數對應的下標,復雜度 O(n).

方法二解答:

 

class Solution 
{
public:
	vector twoSum(vector &numbers, int target) 
	{
		unordered_map mapping;
		vector result;
		for (int i = 0; i < numbers.size(); ++i)
		{
			mapping[numbers[i]] = i;
		}
		for (int i = 0; i < numbers.size(); ++i)
		{
			const int tmp = target - numbers[i];
			if (mapping.find(tmp) != mapping.end() && mapping[tmp]>i)
			{
				result.push_back(i+1);
				result.push_back(mapping[tmp] + 1);
				break;
			}
		}
		return result;
	}
};
在線推送結果為:

 


Question:
Similar to Question [1. Two Sum], except that the input array is already sorted in
ascending order.

問題:假如數組是有序的話我們就可以同時從頭尾開始向中遍歷。

 

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


 

 

 

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