leetcode - 1. Two Sum (java)
2018-01-25 19:19
405 查看
Problem:
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:
解释:给定一个整型数据的数组,找到两个数,加起来等于所给的target的值。返回这两个数在数组中的下标。
(假定都有答案且每个数字只能用一次)
Solve:
1.简单暴力,直接两重循环查找,找到这两个数字就返回结果(时间复杂度O(n^2),AC-39ms)
2.调用JAVA中的map来保存查找数字。将查找交给map降低复杂度,(时间复杂度O(n),AC-9ms)
后记:emmm,很久前就想写点博客记录下,刚好放寒假,科目二挂科 mmp,顺手来写了,代码之前写的,尽量保持一天写一题吧。兴趣使然,想写就写。
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]
解释:给定一个整型数据的数组,找到两个数,加起来等于所给的target的值。返回这两个数在数组中的下标。
(假定都有答案且每个数字只能用一次)
Solve:
1.简单暴力,直接两重循环查找,找到这两个数字就返回结果(时间复杂度O(n^2),AC-39ms)
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[i]+nums[j]==target){ int []re={i,j}; return re; } } } return null; }
2.调用JAVA中的map来保存查找数字。将查找交给map降低复杂度,(时间复杂度O(n),AC-9ms)
public static int[] twoSum1(int[] nums,int target){ HashMap<Integer,Integer> map=new HashMap(); for (int i = 0; i <nums.length ; i++) {//保存至map。 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) {//查找map return new int[] { i, map.get(complement)}; } } return null; }
后记:emmm,很久前就想写点博客记录下,刚好放寒假,科目二挂科 mmp,顺手来写了,代码之前写的,尽量保持一天写一题吧。兴趣使然,想写就写。
相关文章推荐
- 【LeetCode】Two Sum 解题报告(java & python)
- jiler的LeetCode学习笔记 java版本Two Sum
- leetcode_java_第一题 two sum
- 【leetcode with java】1 Two Sum
- LeetCode-java实现-T1-Two Sum
- <LeetCode(Java版)>Two Sum
- Java [leetcode 1] Two Sum
- Java 哈希表运用-LeetCode 1 Two Sum
- [LeetCode][Java] Two Sum
- LeetCode(java)1. Two Sum
- 用java解决LeetCode(1)——Two Sum
- 【LeetCode解题一】Two Sum问题Java解答
- [leetcode NO.1] Two Sum (JAVA)
- LeetCode|Two Sum-java
- [LeetCode] 001. Two Sum (Medium) (C++/Java/Python)
- [LeetCode][1 Two Sum]Java实现
- 【JAVA、C++】LeetCode 001 Two Sum
- leetcode JAVA Search a 2D Matrix 难度系数3 3.25
- (java)leetcode-9
- LeetCode算法问题9 —— Two Sum