从最简单的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].
Accepted 1,973,764 Submissions 4,450,090
最简单系列:通过率也就是不到1/2吧
数组嘛,最直接想到的就是循环。双重循环。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i=0;i< nums.length-1;i++ ){
result[0] =i;
for(int j=i+1;j<nums.length;j++ ){
result[1] = j;
if(nums[i]+nums[j] == target){
return result;
}
}
}
return result;
}
}
找不到应该打印依据或者抛个异常。测试 通过
Runtime: 31 ms
Memory Usage: 36.8 MB
缺点:太慢, 优点:节省内存。
Complexity Analysis
-
Time complexity : O(n^2)O(n2). For each element, we try to find its complement by looping through the rest of array which takes O(n)O(n) time. Therefore, the time complexity is O(n^2)O(n2).
-
Space complexity : O(1)O(1).
改进法:争取降到O(n)
引入hashmap做判断,
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap();
int[] result = new int[2];
for(int i=0;i< nums.length-1;i++ ){
map.put(nums[i],i);
}
for(int j=1;j<nums.length;j++ ){
result[1] = j;
int tmp = target- nums[j];
if(map.containsKey(tmp) && map.get(tmp) != j){
result[0] = map.get(tmp);
return result;
}
}
return result;
}
}
Runtime: 2 ms
Memory Usage: 37.4 MB
比之前快多了,内存有一点增加。
Complexity Analysis:
-
Time complexity : O(n)O(n). We traverse the list containing nn elements exactly twice. Since the hash table reduces the look up time to O(1)O(1), the time complexity is O(n)O(n).
-
Space complexity : O(n)O(n). The extra space required depends on the number of items stored in the hash table, which stores exactly nn elements.
还有更好的方法,。。。。。
习惯了开发工具,直接写代码真不适应。