LeetCode:Two Sum
2015-01-15 12:58
471 查看
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Solutions:
Adding each element to the Hash table takes linear time (O(n)). I store each element in the array as the key and its position as the value. The idea is to find the key value (target - index1) if it's not null (it exists), then index2
is the value of that key. Each lookup takes constant time (O(1)) and in the worst case, it'll run n times.
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Solutions:
Adding each element to the Hash table takes linear time (O(n)). I store each element in the array as the key and its position as the value. The idea is to find the key value (target - index1) if it's not null (it exists), then index2
is the value of that key. Each lookup takes constant time (O(1)) and in the worst case, it'll run n times.
import java.util.HashMap; import java.util.Map; public class Solution { public int[] twoSum(int[] numbers, int target) { int[] solution = new int[2]; Map<Integer, Integer> H = new HashMap<Integer,Integer> (numbers.length); // O(n) time for adding each element to the Hash table. for(int i=0; i<numbers.length; i++) { H.put(numbers[i], i); } // Lookup for element index2 such that index2==(target-index1) (O(1)) // O(1) for each lookup, O(n) total. for(int i=0; i<numbers.length; i++) { if(H.get(target-numbers[i]) != null && H.get(target-numbers[i])!=i) { solution[0] = i+1; solution[1] = H.get(target - numbers[i]) +1; break; } else continue; } return solution; } private int findIndex(int[] numbers, int num, int start){ for(int i = start;i < numbers.length;i++) if(numbers[i] == num) return i; return -1; } }
相关文章推荐
- leetcode Two Sum 每日一题 (。・∀・)ノ゙嗨
- [LeetCode]1.Two Sum
- Two Sum--leetcode
- LeetCode之1—-Two Sum
- Leetcode 1: two Sum
- leetcode第一题(medium)——Two Sum
- Leetcode Two Sum
- Leetcode 1. Two Sum
- LeetCode 1. Two Sum
- 【 LeetCode】 |Two Sum
- [Leetcode 13] 1 Two Sum
- leetcode学习 1.two sum
- 【LeetCode】1. Two Sum
- LeetCode Two Sum
- LeetCode - Two Sum
- leetcode 151 Two Sum
- leetcode 1. Two Sum
- LeetCode----Two Sum
- 【Leetcode】Two sum
- [LeetCode] Two Sum