package LeetCode;
import java.util.HashMap;
public class LeetCode1 {
// 1. Two Sum
// https://leetcode.com/problems/two-sum/description/
// æ¶é´å¤æåº¦ï¼O(n)
// 空é´å¤æåº¦ï¼O(n)
public int[] twoSum(int[] nums, int target) {
HashMap record = new HashMap();
for(int i = 0 ; i < nums.length; i ++){
int complement = target - nums[i];
if(record.containsKey(complement)){
int[] res = {i, record.get(complement)};
return res;
}
record.put(nums[i], i);
}
throw new IllegalStateException("the input has no solution");
}
// ç±äºé¢ç®ä¸åªè¦æ±æ±åºå¯ä¸çä¸ä¸ªè§£ãå æ¤å¯ä»¥å¨æåçæ¶åéåæ´ä¸ªæ°ç», å°æ°ç»ä¸çæ¯ä¸ªæ°åçç´¢å¼æ¾å¨mapä¸ã
// æ¤æ¶, recordä¸è®°å½çæ°¸è¿æ¯æ¯ä¸ä¸ªæ°åæååºç°çä½ç½®ã
// èå¯¹äº target = 2*açæ
åµ, 妿numsä¸æä¸¤ä¸ªæä¸¤ä¸ªä»¥ä¸a,
// æä»¬å¨æ«ææ¶ä¼å
çå°ç¬¬ä¸ä¸ªa, èä»record䏿¿å°çæ¯æåä¸ä¸ªa :)
public int[] twoSum2(int[] nums, int target) {
HashMap record = new HashMap();
for(int i = 0 ; i < nums.length ; i ++)
record.put(nums[i], i);
for(int i = 0 ; i < nums.length; i ++){
if(record.containsKey(target - nums[i]))
// éå¯¹åªæä¸ä¸ªè§£ï¼æä»¥å¯ä»¥ç¨ç´¢å¼çæ¹å¼å¤æ(ä½è¿æ¯ç¨å¼æ¥å¤æææä¸äº)...
if(record.get(target - nums[i]) != i){
int[] res = {i, record.get(target - nums[i])};
return res;
}
record.put(nums[i], i);
}
throw new IllegalStateException("the input has no solution");
}
}