文章目录
- 题目
- c++版本
- java版本
- 利用hashmap
- 正确做法
题目
- Two Sum
Easy
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++版本
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ivec;
for(int i = 0; i < nums.size() - 1; i++){
for(int j = i + 1; j < nums.size(); j++)
if(nums[i] + nums[j] == target){
ivec.push_back(i);
ivec.push_back(j);
break;
}
}
return ivec;
}
};
java版本
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ret = new int[2];
for(int i = 0; i < nums.length; i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
ret[0] = i;
ret[1] = j;
break;
}
}
}
return ret;
}
}
时间复杂度为O(n^2)
利用hashmap
错误做法
改进
正确做法
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ret = new int[2];
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int diff = target - nums[i];
if(map.containsKey(diff)){
ret[0] = i;
ret[1] = map.get(diff);
break;
}
map.put(nums[i],i);
}
return ret;
}
}
时间复杂度为O(n)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)