1 Two Sum

来源:互联网 发布:襄阳樊城区网络问政 编辑:程序博客网 时间:2024/06/06 17:52

这题到处都有。。。无语。。。

我看到了就只能在联系一遍。。。

之前代码:

public class Solution {    public int[] twoSum(int[] nums, int target) {        HashMap<Integer, Integer> map= new HashMap<>();        int[] result= new int[2];        for(int i=0; i<nums.length; i++){            if(map.containsKey(target-nums[i])){                result[0]=map.get(target-nums[i]);                result[1]=i;                break;            }            else map.put(nums[i], i);        }        return result;    }}

今天的代码,3 min 完成,few typo: forget the the word: new, and  a semicolon ;    

public class Solution {    public int[] twoSum(int[] nums, int target) {        int len= nums.length;        //if(len==0) return false; // the Q said there is one sulution                HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); //<[index], index>         int[] result= new int[2];        for(int i=0; i<len; i++){            if(map.containsKey(target-nums[i])){                result[0]=map.get(target-nums[i]);                result[1]=i;                break; // since there is only one solution;            }            else map.put(nums[i], i);        }        return result;        }}


0 0