1,暴力破解法
就是使用两个for循环,这种效率很差
public int[] twoSum(int[] nums, int target) { int length = nums.length; for (int i = 0; i < length - 1; i++) { for (int j = i + 1; j < length; j++) if (nums[i] + nums[j] == target) return new int[]{i+1, j+1}; } return new int[]{-1, -1}; }
2,使用HashMap解决
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (m.get(target - nums[i]) != null) { return new int[]{m.get(target - nums[i])+1, i+1}; } m.put(nums[i], i); } return new int[]{0, 0}; }
我把部分算法题整理成了PDF文档,截止目前总共有900多页,大家可以下载阅读
链接:https://pan.baidu.com/s/1hjwK0ZeRxYGB8lIkbKuQgQ
提取码:6666