给定一个整数数组 nums 和一个整数目标值 target,在该数组中找出和为目标值 target 的两个整数,并返回数组下标。

解题思路:
暴力法:最常见的就是双层for循环,拿每个元素和其他元素求和,满足条件返回,时间复杂度O(n*n);通过hashMap方式处理,一层for循环,对于每一个元素 X 到hash中查找是否存在 target-X ,不满足条件将 X 放到map中,时间复杂度O(n);代码片段:
private static int[] twoSum(int[] nums, int target) { int[] res = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int temp = target - nums[i]; if (map.containsKey(temp)) { res[0] = map.get(temp); res[1] = i; } map.put(nums[i], i); } return res; }
本地运行结果:
LeetCode执行结果:好像不是很理想[笑哭]
每天一道算法题,欢迎大佬沟通指正~


还没有评论,来说两句吧...