#1 Two Sum(Easy)
2017-02-10 17:37
274 查看
题目描述
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, and you may not use the same element twice. Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
My Solution
简单暴力的双重循环public class Solution { public int[] twoSum(int[] nums, int target) { int len = nums.length; int[] ret = new int[2]; for(int i = 0 ; i < len ; i++) for(int j = i + 1 ; j < len ; j++){ if(nums[i] + nums[j] == target){ ret[0] = i; ret[1] = j; return ret; } } return null; } }
nums[i] + nums[j] == target 存在缺陷,应改为 nums[i] == target - nums[j] 避免超出int的范围。
Editorial Solution
上述解法为O(n^2)的时间复杂度,O(1)的空间复杂度。可以利用hashMap的思想使得复杂度都变为O(n)。Map的使用可以预处理,也可以一次遍历的过程中处理。import java.util.HashMap; import java.util.Map; public class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<Integer,Integer>(); for(int i = 0 ; i < nums.length ; i++){ int complement = target - nums[i]; if(map.containsKey(complement)){ return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return null; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode刷题,没想到这么难搞!
- 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... 题解