LeetCode-1. Two Sumhttps://leetcode.com/problems/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].
解题思路
【C++解法】
1. 暴力双重遍历
//直接一点,时间复杂度O(n^2)高一些
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> SumIndex(2,-1);
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if(nums[j] == target - nums[i]) {
SumIndex[0] = i;
SumIndex[1] = j;
}
}
}
return SumIndex;
}
};
2. map
//未说明是否排序,构造一个map
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> SumIndex;
unordered_map<int,int> SumMap;
for (int i = 0; i < nums.size(); i++) {
SumMap[nums[i]] = i;
}
for (int i = 0; i < nums.size(); i++) {
int other = target - nums[i];
if (SumMap.count(other) && SumMap[other] != i) {
SumIndex.push_back(i);
SumIndex.push_back(SumMap[other]);
return SumIndex;
}
}
return SumIndex;
}
};
【Java】
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i=0; i<nums.length; i++) {map.put(nums[i], i);}
for (int i=0; i<nums.length; i++) {
int other = target - nums[i];
if (map.containsKey(other) && map.get(other) != i) {
return new int[]{i, map.get(other)};
}
}
return null;
}
}