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.
(译:给定一个整数数组,返回两个数字的索引,使它们相加得到一个特定目标值。您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。)
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]
代码实现:(参考)
1 import java.util.HashMap; 2 import java.util.Map; 3 4 public class Solution { 5 public static int[] twoSum(int[] nums, int target) { 6 int[] result = new int[2]; 7 Map<Integer,Integer> map = new HashMap(); 8 for(int i=0; i<nums.length; i++){ 9 if(map.containsKey(target - nums[i])){ 10 if(map.get(target - nums[i]) > i){ 11 result[0] = i; 12 result[1] = map.get(target - nums[i]); 13 }else{ 14 result[1] = i; 15 result[0] = map.get(target - nums[i]); 16 } 17 return result; 18 } 19 map.put(nums[i], i); 20 } 21 return result; 22 } 23 24 public static void main(String[] args) { 25 int[] nums = {3,2,4}; 26 int target = 6; 27 int[] result = new int[2]; 28 result = twoSum(nums,target); 29 System.out.println(result[0] + " " + result[1]); 30 } 31 }
原文地址:https://www.cnblogs.com/dwystyle/p/8440083.html
时间: 2024-10-15 21:09:52