程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
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

我自己寫了一個解法:

是設置了一個結構體存儲原下標和相應數值,然後設置該結構體類型的容器並對其進行排序後處理。代碼如下:

#include 
#include 
#include
using namespace std;
typedef struct m_data
{
	int num;
	int index;
}m_data;
bool SortBynum(const m_data &R1,const m_data &R2)//容器的比較函數
{  
	return (R1.num < R2.num);//升序排列   
} 


 vector twoSum(vector &numbers, int target) 
 {
	 vector  mydata;
	 for (int i = 0; i < numbers.size(); i++)//掃描遍歷復制
	 {
		 m_data temp;
		 temp.num = numbers[i];
		 temp.index = i;
		 mydata.push_back(temp);
	 }

	 vector result;
	 sort(mydata.begin(),mydata.end(),SortBynum);  //按升序排列
	 for (int i = 0; i < mydata.size(); i++)
	 {
		cout< mydata[j].index )
				{
					result.push_back(mydata[j].index);
					result.push_back(mydata[i].index);
				}
				else
				{
					result.push_back(mydata[i].index + 1);
					result.push_back(mydata[j].index + 1);
				}
				cout< target)//大於時,直接進入下一次的循環,節約時間成本
			{
				break;
			}
		 }
	
	return result;
 }
//測試用
 int main()
 {
	 vector  numbers;
	 numbers.push_back(3);
	 numbers.push_back(2);	
	 numbers.push_back(4);
	 numbers.push_back(9);
	 twoSum(numbers,7);
	 system("pause");
	 return 1;
 }

但是leecode說無法編譯sort函數,不知道如何加入#include這個頭文件,於是在網上查了下有沒有其他解法,找到一個利用map實現的方法,覺得很棒,原文地址:http://blog.csdn.net/pickless/article/details/8995612,代碼很短小精悍,也節省了一部分時間復雜度,非常喜歡,記錄下來:

代碼如下:

#include 
#include 
#include
#include 
using namespace std;


vector twoSum(vector &numbers, int target) 
{
	vector ans;  
	map numbersMap;  //key為數值 value為對應的下標+1
	map::iterator iter;  
	for (int i = 0; i < numbers.size(); i++) 
	{
		iter = numbersMap.find(target - numbers[i]);  //要找的key
		if (iter != numbersMap.end()) //如果找到
		{  
			ans.push_back(iter->second);  //存儲的內容
			ans.push_back(i + 1);  
			break;  
		} 
		else 
		{  
			numbersMap[numbers[i]] = i + 1;  
		}  
	}  
	cout< numbers;
	numbers.push_back(3);
	numbers.push_back(2);	
	numbers.push_back(4);
	
	twoSum(numbers,6);
	system("pause");
	return 1;
}



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