1、暴力枚举
- num.length 获取长度
- 返回数组 int[]{i,j}
class Solution {public int[] twoSum(int[] nums, int target) {int n = nums.length;for(int i = 0;i<n-1;i++){for(int j=i+1;j<n;j++){if(nums[i]+nums[j] == target){return new int[]{i,j};}}}return new int[-1];}}
2、哈希
为什么是n-1? 因为前n-1个数据才需要存入哈希表,假设一直遍历到最后一个元素,拿着最后一个元素去比较,发现查到了就直接返回坐标了;没查到就是失败了,都不需要再存入。
- 哈希表定义:n-1长度的哈希表 Map<Integer,Integer> hashMap = new HashMap<>(n-1); 指定长度防止内存溢出
- 哈希表中是否存在key元素 hashMap.containsKey(key) true/false
- get取元素,put存元素
- 哈希结构类似于数组 key,id样式
1 class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 int n = nums.length; 4 Map<Integer,Integer> hashMap = new HashMap<>(n-1); //为什么是n-1呢? 5 hashMap.put(nums[0],0); 6 for(int i = 1;i<n;i++){ 7 int key = target- nums[i]; 8 if(hashMap.containsKey(key)){ 9 return new int[]{i, hashMap.get(key)}; 10 } 11 hashMap.put(nums[i],i); 12 } 13 return new int[-1]; 14 } 15 }