目录
- 1、Question——TwoSum
1、Question——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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Answer
package com.demo.leetcode001; import java.util.HashMap; public class twoSum { public static int[] iTwoSum(int[] nums, int target){ HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); int[] res = new int[2]; for(int i = 0; i < nums.length; i++){ if(m.containsKey(target - nums[i])){ res[1] = i; res[0] = m.get(target - nums[i]); break; } m.put(nums[i], i); } return res; } public static void main(String[] args) { int[] nums = {2, 7, 11, 15}; int target = 9; int[] res = iTwoSum(nums,target); System.out.println(res[0]); System.out.println(res[1]); } } |