Leetcode刷题小记(1)--T1

1. Two Sum

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 would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        unordered_map hash_table;
        for (int i = 0; i < nums.size(); ++i){
            if (hash_table.find(target - nums[i]) != hash_table.end())
            return vector{ hash_table[target - nums[i]], i }; // 12ms beats 97.81%
        hash_table.insert(pair(nums[i], i));
        }
        return vector();
    }
};

主要运行了   STL库中的数据结构  unordered_map

 

vs测试代码:

#include
#include
#include
using namespace std;

class Solution {
public:
	vector twoSum(vector& nums, int target) {
		unordered_map hash_table;
		for (int i = 0; i < nums.size(); ++i) {
			if (hash_table.find(target - nums[i]) != hash_table.end())
				return vector{ hash_table[target - nums[i]], i }; // 12ms beats 97.81%
			hash_table.insert(pair(nums[i], i));
		}
		return vector();
	}
};

int main() {
	Solution solution;
	vector aaa{ 2,7,11,15 };
	int target = 9;
	cout << solution.twoSum(aaa, target)[0]<<" " << solution.twoSum(aaa, target)[1] <

 

你可能感兴趣的:(算法,基础算法)