Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
This line in the first position of the problem I do now, nothing else to say. This can be easily solved with hashmap.
Note, however, that because you cannot return 0, it is possible to generate 0 by using the Map.get () method directly, so return i is +1.
The code is as follows. ~
public class Solution {public int[] Twosum (int[] nums, int target) { hashmap<integer,integer> result=new H Ashmap<> (); for (int i=0;i<nums.length;i++) { if (Result.containskey (Target-nums[i])) { return new Int[]{result.get ( Target-nums[i]) +1,i+1}; } else{ result.put (nums[i],i); } } return null;} }
[Leetcode] The Sum of