Topics
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, target=9
Output: index1=1, index2=2
Thinking of solving problems
Use brute force solution. Time Complexity O (n^2), spatial complexity O (1).
Use the hash table to store the number of accesses. Time complexity O (n), spatial complexity O (n). √
Code
Int[] Twosum (int[] nums, int target) {Hashmap<integer, integer> HM = new Hashmap<integer, integer> (); int[] Ind Ex=new int[2];for (int i=0;; i++) {if (Hm.containskey (Target-nums[i])) {index[0] = Hm.get (Target-nums[i]) +1;index[1] = I+1;break;} Else{hm.put (Nums[i],i);}} return index;}
Run results
Submit Time |
Status |
Run Time |
Language |
Minutes ago |
Accepted |
380 ms |
Java |
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
1.Two Sum