https://leetcode.com/problems/two-sum/
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
Today starts from the zero single row Leetcode, commemorates some
This is a simple question, but there are several details to note. This problem requires the return of the subscript, note is starting from 1.
Solution One: Double pointer brute force solution, Time Complexity O (n2), Space O (1)
Public classSolution { Public int[] Twosum (int[] Nums,inttarget) { int[] res =New int[2]; for(inti = 0; i < nums.length-1; i++){ for(intj = i+1; J < Nums.length; J + +){ if(Nums[i]+nums[j] = =target) {res[0] = i+1; res[1] = j+1; Break; } } } returnRes; }}
Solution 2:hashtable, Time complexity O (n), Spatial complexity O (1)
Public classSolution { Public int[] Twosum (int[] Nums,inttarget) { int[] res =New int[2]; Map<integer, integer> map =NewHashmap<>(); for(inti = 0; i < nums.length; i++){ if(Map.containskey (Nums[i])) {res[0] = Map.get (Nums[i]) +1; res[1] = i+1; Break; }Else{map.put (target-Nums[i], i); } } returnRes; }}
Leetcode (1) Sum