LeetCode1. Two Sum(两数之和)


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.

Example: 
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

例:给定 nums = [2, 7, 11, 15], target = 9 
因为 nums[0] + nums[1] = 2 + 7 = 9 
所以返回 [0, 1]

public class Solution {
	public static int[] twoSum(int[] nums, int target) {
		Map<Integer, Integer> map = new HashMap<>();
		int len = nums.length;
		for (int i = 0; i < len; i++) {
			if (map.containsKey(target - nums[i]))
				return new int[] { map.get(target - nums[i]), i };
			map.put(nums[i], i);
		}
		return null;
	}

测试代码

public class Test {
	public static void main(String[] args) {
		int[] a = { 1, 8, 6, 2, 5, 10 };
		int m = 9;
		System.out.println(Arrays.toString(Solution.twoSum(a, 9)));
	}
}

运行结果:[0, 1]

猜你喜欢

转载自blog.csdn.net/qq_26891141/article/details/85111216