1. Given an array of integers, return indices of the both numbers such that they add-to a specific target.
Problem:
1. Array is ordered
2. Array sorting
Sorting array Arrays. Sort(iarr)
Method 1:o (n^2)
Public classSolution { Public int[] Twosum (int[] Nums,inttarget) { int[] result =New int[2]; for(inti = 0; i < nums.length; i++){ for(intj = i+1; J < Nums.length; J + +){ if(Nums[i] + nums[j] = =target) {Result [0] =i; result [1] =J; } } } returnresult; }}
2. The second sum II Input array is sorted (HashMap, no same element
Given an array of integers so is already
sorted in ascending order, find, numbers such, 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.
Public classSolution { Public int[] Twosum (int[] Nums,inttarget) {
int[] result =New int[2]; HashMap<integer, integer> HM =NewHashmap<integer, integer>(); for(inti = 0; i < nums.length; i++) {hm.put (nums[i], i); } for(inti = 0; i < nums.length; i++){ if(Hm.containskey (target-nums[i]) && Target! = 2 *Nums[i]) {result[0] =i; result[1] = Hm.get (target-Nums[i]); Break; } } returnresult; }
}
3. The sum III
1. Sum I & II & III