个人记录-LeetCode 1.Two Sum
2016-08-14 11:33
411 查看
问题:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
代码示例:
1、暴力解法
2、利用hashMap来快速查找
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
代码示例:
1、暴力解法
public class Solution { public int[] twoSum(int[] nums, int target) { if(nums == null || nums.length < 2) { return null; } for(int i = 0; i < nums.length - 1; ++i) { for (int j = i + 1; j < nums.length; ++j) { if (nums[i] + nums[j] == target) { return new int[] {i, j}; } } } return null; } }
2、利用hashMap来快速查找
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { //求出需要的匹配数字 int complement = target - nums[i]; //判断匹配数字是否已经加入到map中 //更快,而且可以避免加入重复数字时HashMap的替换 if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); }
相关文章推荐
- 个人记录-LeetCode 2.Add Two Numbers
- 个人记录-LeetCode 4.Median of Two Sorted Arrays
- 个人记录-LeetCode 20. Valid Parentheses
- 个人记录-LeetCode 25. Reverse Nodes in k-Group
- 个人记录-LeetCode 24. Swap Nodes in Pairs
- 【LeetCode刷题记录】Two Sum
- 个人记录-LeetCode 29. Divide Two Integers
- 个人记录-LeetCode 18. 4Sum
- 个人记录-LeetCode 17. Letter Combinations of a Phone Number
- 个人记录-LeetCode 27. Remove Element
- 个人记录-LeetCode 5.Longest Palindromic Substring
- 个人记录-LeetCode 10.Regular Expression Matching
- 个人记录-LeetCode 9.Palindrome Number
- 个人记录-LeetCode 19. Remove Nth Node From End of List
- 个人记录-LeetCode 14. Longest Common Prefix
- 个人记录-LeetCode 3.Longest Substring Without Repeating Characters
- 个人记录-LeetCode 8.String to Integer (atoi)
- 个人记录-LeetCode 12. Integer to Roman
- 个人记录-LeetCode 22. Generate Parentheses
- 个人记录-LeetCode 28. Implement strStr()