LeetCode(java)1. Two Sum
2016-04-06 12:45
363 查看
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.
Example:
一开始的解法为穷举法:时间复杂度为O(n²)
其实如果不惜内存的话可以建立两个超大的数组,第一个用于存放正数(例如7则将arr[7]置1),另一个存放负数(例如-11则将arrsc[11]置1)。
数组的操作应该比HashMap更快
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
一开始的解法为穷举法:时间复杂度为O(n²)
public class Solution { public int[] twoSum(int[] nums, int target) { for(int i=0;i<nums.length;i++) { for(int j=i+1;j<nums.length;j++) { if(nums[i]+nums[j] == target) return new int[]{i+1,j+1}; } } return null; } }后来发现有点慢:改进了算法,使用了HashMap,时间复杂度变为O(n),通过时间为7ms
public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); Integer lc; for(int i=0;i<nums.length;i++) { map.put(nums[i], i); } for(int i=0;i<nums.length;i++) { if((lc = map.get(new Integer(target-nums[i])))!=null) { if(lc!=i) return new int[]{i,lc}; } } return null; } }
其实如果不惜内存的话可以建立两个超大的数组,第一个用于存放正数(例如7则将arr[7]置1),另一个存放负数(例如-11则将arrsc[11]置1)。
数组的操作应该比HashMap更快
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解