1. 两数之和
简单
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
解1:拿到题目,看见简单标签,直观感受直接暴力。时间复杂度:O(n⒉)
class Solution { public int[] twoSum(int[] nums, int target) { int n = nums.length; for(int i = 0; i < n; i ++){ for(int j = i + 1; j < n; j ++){ if(nums[i] + nums[j] == target) return new int[]{i, j}; } } return null; } }
执行用时分布 50ms 击败27.46%
解2:优化,想法:如果这是一个有序的数组那么就,只需要用双指针指向两边逐渐向中间靠拢,则遍历n次就可保证得到。进行排序后,时间复杂度为:O(nlogn) 因为要得到数组下标而排序会破坏下标索引,这个时候还需要用HashMap将其索引给存储下来。
class Solution { public int[] twoSum(int[] nums, int target) { // 存储元素及其原始索引 Map<Integer, List<Integer>> indexMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { indexMap.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(i); } // 对数组进行排序 Arrays.sort(nums); // 双指针法 int left = 0, right = nums.length - 1; while (left < right) { int sum = nums[left] + nums[right]; if (sum == target) { int[] result = new int[2]; if (nums[left] == nums[right]) { // 如果两个元素相等,从 indexMap 中取出对应的两个索引 result[0] = indexMap.get(nums[left]).get(0); result[1] = indexMap.get(nums[left]).get(1); } else { // 从 indexMap 中取出对应的索引 result[0] = indexMap.get(nums[left]).get(0); result[1] = indexMap.get(nums[right]).get(0); } return result; } else if (sum < target) { left++; } else { right--; } } return null; } }
执行用时分布 8ms 击败34.16%
深度优化:有没有一个结构能将前面遍历过的数都存储起来,往后遍历时只需要用目标值减去当前遍历到的值,然后判断之前是否有存储过这么一个值(有的 兄弟有的)。这样只需要遍历一次,时间复杂度:O(n)
class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> hashMap = new HashMap<>(); int len = nums.length; for(int i = 0; i < len; i ++){ if(hashMap.containsKey(target - nums[i])) return new int[]{hashMap.get(target - nums[i]), i}; hashMap.put(nums[i], i); } return null; } }
执行用时分布 2ms 击败99.8%
这里为什么要用数组的值作为key?
答:这里的核心在于,对于数组中的每个元素 num,需要快速判断数组里是否存在另一个元素 target - num,并且要知道它们各自的索引。containsKey 用于快速检查某个键是否存在于 HashMap 中的,其时间复杂度为 O(1) 。虽然containsValue方法可以检查 HashMap中是否存在指定的值。不过,它的时间复杂度是 O(n),因为它需要遍历 HashMap 里的所有值来进行检查。