LeetCode-TwoSum

题目:

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, and you may not use the same element twice.

给定一个非负整数数组和一个特定的数字,返回数组中两数相加等于给定数的下标。


示例:

给定数组:Given nums = [2, 7, 11, 15], 和一个指定的数:target = 9,
因为:Because nums[0] + nums[1] = 2 + 7 = 9,
返回:return [0, 1].

解法:

public class TwoSum {

    /**
     * @param nums input array of Integers
     * @param target target = nums[index1] + nums[index2]
     * @return result array [index1, index2] and index1 < index2
     */
    public int[] twoSum(int[] nums, int target) {
        int[] result = null;
        HashMap tempMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (tempMap.get(nums[i]) != null) {
                result = new int []{tempMap.get(nums[i]), i};
                return result;
            }
            tempMap.put(target - nums[i], i);
        }
        return result;
    }

    public static void main(String[] args) {
        TwoSum solution = new TwoSum();
        int[] result = solution.twoSum(new int[] {3, 2, 4}, 6);
        System.out.print(result[0] + "," + result[1]);
    }
}


欢迎关注码农组织:码者荣耀,微信公众号:mazherongyao

LeetCode-TwoSum_第1张图片

你可能感兴趣的:(LeetCode)