leetcode第一题(medium)——Two Sum
2015-05-20 16:08
204 查看
题目描述如下:
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
看到题目第一眼。首先想到的是进行两次循环来找出两个数之和来满足target,当然这是最自然的一种想法,时间复杂度为O(n^2)
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
看到题目第一眼。首先想到的是进行两次循环来找出两个数之和来满足target,当然这是最自然的一种想法,时间复杂度为O(n^2)
public static int[] twoSum(int[] nums, int target) { int[] ret = new int[2]; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { ret[0] = i + 1; ret[1] = j + 1; } } } return ret; }第二种相对于第一种解法简便很多,时间复杂度为O(n):
public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] result = new int[2]; for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i])) { int index = map.get(nums[i]); result[0] = index+1 ; result[1] = i+1; break; } else { map.put(target - nums[i], i); } } return result; }
相关文章推荐
- leetcode第一题--two sum
- leetcode_java_第一题 two sum
- leetcode------第一题 Two Sum
- leetcode第一题two sum
- LeetCode 第一题 Two Sum
- 算法分析与设计丨第一周丨LeetCode(2)——Different Ways to Add Parentheses(Medium)
- Leetcode第一题--------- Two Sum
- leetcode第一刷_Two sum
- leetcode 第一题 two sum
- 【leetcode】two sum --medium
- LeetCode 第一题,Two Sum
- [LeetCode] 001. Two Sum (Medium) (C++/Java/Python)
- Leetcode第一题_Two Sum
- 我的LeetCode第一弹 Leetcode: Two Sum
- 【Leetcode】【Medium】Two Sum
- [Leetcode 1, Medium] Two sum
- 算法分析与设计丨第一周丨 LeetCode(1)——Two Sum
- Leetcode 之第一题 two sum
- LeetCode第一题Two Sum
- 题解——Leetcode 240. Search a 2D Matrix II 难度:Medium