LeetCode1. Two Sum
题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
我的解决方法,弱爆了但是还是要贴出来:
1 package Mine; 2 3 public class TwoSum01 { 4 public int[] twoSum(int[] nums, int target) { 5 int[] result = new int[2]; 6 int length = nums.length; 7 8 for (int i = 0; i < length ; i ++){ 9 for (int j = i+1 ; j < length ; j ++) { 10 if(nums[i] + nums[j] == target) { 11 result[0] = i; 12 result[1] = j; 13 } 14 } 15 } 16 return result; 17 } 18 }
别人家孩子:
1 package BOOK; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 public class TwoSum01 { 7 public int[] twoSum(int[] nums, int target) { 8 Map<Integer, Integer> map = new HashMap<>(); 9 for(int i = 0; i < nums.length; i ++) { 10 int x = nums[i]; 11 if(map.containsKey(target - x)) { 12 return new int[] {map.get(target -x) , i}; 13 } 14 map.put(x, i); 15 } 16 throw new IllegalArgumentException("No two sum solution"); 17 } 18 }
浙公网安备 33010602011771号