1. Two Sum

 

解法一: 两重循环, 找到这两个加和为target的数

#include <iostream>
#include <vector>

using namespace std;

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

void print(const vector<int>& v)
{
	for(int e : v)
		cout << e << " ";
	cout << endl;
}

int main()
{
	const int a[] = {2,7,11,15};
	vector<int> v(a, a + sizeof(a)/sizeof(int));
	
	int target = 9;
	
	print(Solution().twoSum(v, target));
	
	return 0;
}

  

解法二: 先将数组中所有的数存放到hashmap中, 再遍历该数组, 判断target-当前的数字nums[i]是否已在hashmap中, 若存在, 并且索引值不同, 则返回, 否则, 继续循环

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    	
    	unordered_map<int, int> record;
    	for(int i = 0; i < nums.size(); ++ i) {
    		record[nums[i]] = i;
		}
		
		for(int i = 0; i < nums.size(); ++ i) {
			
			int complement = target - nums[i];
			unordered_map<int, int>::iterator it = record.find(complement);
			if(it != record.end() && it->second != i)
				return {i, it->second};
		}
		
    }
};

void print(const vector<int>& v)
{
	for(int e : v)
		cout << e << " ";
	cout << endl;
}

int main()
{
	const int a[] = {1,2,42,42,7,65};
	vector<int> v(a, a + sizeof(a)/sizeof(int));
	
	int target = 84;
	
	print(Solution().twoSum(v, target));
	
	return 0;
}

  

解法三: 判断当前的(target - nums[i])是否在nums[i]之前的数中存在, 若存在则返回, 若不存在, 则将该数存放到hashmap中
#include <iostream>
#include <vector>
#include <exception>
#include <unordered_map>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {

		unordered_map<int, int> record;
		for(int i = 0; i < nums.size(); ++ i) {
			
			int complement = target - nums[i];
			if(record.find(complement) != record.end()) {
				
				int res[] = {i, record[complement]};
				return vector<int>(res, res + 2);
			} 
			else {
				record[nums[i]] = i;
			}
		}
		
    }
};

void print(const vector<int>& v)
{
	for(int e : v) 
		cout << e << " "; 
	cout << endl;
}

int main()
{
	const int a[] = {2,7,11,15};
	vector<int> nums(a, a + sizeof(a)/sizeof(int));
	
	int target = 9;
	
	print(Solution().twoSum(nums, target));
	
	return 0;
}

  

posted @ 2019-07-08 14:05  青衫客36  阅读(157)  评论(0编辑  收藏  举报