两数之和
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; } }
方法二:哈希表
class Solution { public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; if(nums == null || nums.length == 0){ return res; } Mapmap = new HashMap<>(); for(int i = 0;i < nums.length;i++){ int temp = target - nums[i]; if(map.containsKey(temp)){ res[1] = i; res[0] = map.get(temp); } map.put(nums[i],i); } return res; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)