leetcode题目之两数求和
2017-03-15 11:04
218 查看
题目很简单,返回数组中等于目标的两数的下标。用了两种方法去求解。第一种两层循环,时间复杂度O(n^2) 第二种用了hashmap。时间复杂度O(n).
question:
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:
解题 法1:
法2:
测试:
输出:[0,3]
question:
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].
解题 法1:
public static 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[j] == target - nums[i]) { return new int[] { i, j }; } } } throw new IllegalArgumentException("No two sum solution"); }
法2:
public static int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { return new int[] { i, map.get(complement) }; } } throw new IllegalArgumentException("No two sum solution"); }
测试:
public static void main(String[] args) { int[] nums={1,0,4,8}; twoSum(nums,9); int[] num1=twoSum(nums,9); System.out.println(Arrays.toString(num1)); }
输出:[0,3]
相关文章推荐
- [Leetcode][求和问题2Sum/3Sum/4Sum/KSum]相关题目汇总/分析/总结
- 167.leetcode Two Sum II - Input array is sorted(medium)[两数求和固定值]
- LeetCode 题目之 数组两数之和问题
- leetcode 第15题:两数求和的扩展
- leetcode题目 寻找和为SUM的两数(O(nlogn)和O(n)解法)
- leetcode求和题目
- 【LeetCode题目记录-2】从前序遍历和中序遍历构建二叉树
- 我的LeetCode 题目汇总
- LeetCode题目:3. Longest Substring Without Repeating Characters
- leetcode题目难度及面试频率
- leetcode刷题目 ,总结,记录,备忘206
- LeetCode算法题目:Search a 2D Matrix
- leetcode 214:Shortest Palindrome 题目分析 与使用KMP算法的java实现
- [Leetcode题目]234. Palindrome Linked List
- 链表:链表两数相加( LeetCode 2. Add Two Numbers(两数相加))
- leetcode做题总结,题目Integer to Roman 2012/01/15
- nyoj题目22:素数求和问题
- [LeetCode]371.Sum of Two Integers两数相加
- 【python】【leetcode】【算法题目7—Reverse Integer】
- LeetCode 题目 4. Median of Two Sorted Arrays