建立測試案例
public class LeetCode1TwoSumTest {
final LeetCode1TwoSum twoSum = new LeetCode1TwoSum();
/**
* Example:
* Given nums = [2, 7, 11, 15], target = 9,
* Because nums[0] + nums[1] = 2 + 7 = 9,
* return [0, 1].
*/
@Test
public void test1() {
final int[] nums = new int[]{2, 7, 11, 15};
final int target = 9;
int[] act = twoSum.twoSum(nums, target);
Assert.assertTrue(IntStream.of(act).anyMatch(x -> x == 0));
Assert.assertTrue(IntStream.of(act).anyMatch(x -> x == 1));
}
@Test
public void test2() {
final int[] nums = new int[]{3, 3};
final int target = 6;
int[] act = twoSum.twoSum(nums, target);
Assert.assertTrue(IntStream.of(act).anyMatch(x -> x == 0));
Assert.assertTrue(IntStream.of(act).anyMatch(x -> x == 1));
}
@Test
public void test3() {
final int[] nums = new int[]{3, 2, 4};
final int target = 6;
int[] act = twoSum.twoSum(nums, target);
Assert.assertTrue(IntStream.of(act).anyMatch(x -> x == 1));
Assert.assertTrue(IntStream.of(act).anyMatch(x -> x == 2));
}
}
Solution
public class LeetCode1TwoSum {
public int[] twoSum(final int[] nums, final int target) {
// 用來存放 target - n , HashMap
HashMap map = new HashMap<>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
// 如果 map 有(target - n) 的值, 依序將 index 存入 result, 回傳 result
if (map.containsKey(nums[i])) {
int index = map.get(nums[i]);
result[0] = index;
result[1] = i;
return result;
} else {
// 計算目前 index , 相差(target - n) 才會等於 target
map.put(target - nums[i], i);
}
}
return result;
}
}
沒有留言:
張貼留言