[leetcode][easy]Two Sum

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        if (nums == null || nums.length == 0) {
            return result;
        }
        HashMap<Integer, Integer> valueIndexMap = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            int rest = target - nums[i];
            Integer leftIndex = valueIndexMap.get(rest);
            if (leftIndex != null) {
                result[0] = leftIndex;
                result[1] = i;
                return result;
            }
            valueIndexMap.put(nums[i], i);
        }
        return result;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章