目录
- 题目:
- 方法:
- 暴力代码:
- 优化后代码:
题目:
链接: link
方法:
暴力代码:
public int[] twoSum(int[] nums, int target) {解法一:暴力解法:int n = nums.length;for(int i = 1; i <= n; i++)for(int j = i-1; j >= 0; j--){if(target == nums[i] + nums[j]){return new int[]{i,j};}}return null; }
优化后代码:
class Solution {//解法二:用哈希表优化:Map<Integer,Integer> hash = new HashMap<>();//<nums[i],i>for(int i = 0; i < nums.length; i++){int find = target - nums[i];if(hash.containsKey(find)){return new int[]{i,hash.get(find)};}hash.put(nums[i],i);}return null;}
}