leetcode Two Sum(Java)
2017-06-05 16:19
295 查看
题目链接:https://leetcode.com/problems/two-sum/#/description
遍历问题
暴力解法:遍历数组,算法复杂度O(n²)
hashMap:虽然少了一次循环,但是HashMap的查找value值仍需要额外的时间
public class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length < 1)
return new int[]{-1, -1};
HashMap<Integer, Integer> test = new HashMap<Integer, Integer>();
for(int i = 0 ; i < nums.length ; ++i)
{
int complement = target-nums[i];
if(test.containsKey(complement))
{
return new int[]{test.get(complement), i};
}
else
{
test.put(nums[i], i);
}
}
return new int[]{-1, -1};
}
}
遍历问题
暴力解法:遍历数组,算法复杂度O(n²)
public class Solution { public int[] twoSum(int[] nums, int target) { int[] test = {0,0}; for(int i = 0 ; i < nums.length ; ++i) { for(int j = i+1 ; j < nums.length ; ++j) { if( target == (nums[i] + nums[j]) ) { test[0] = i; test[1] = j; return test; } } } return test; } }
hashMap:虽然少了一次循环,但是HashMap的查找value值仍需要额外的时间
public class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length < 1)
return new int[]{-1, -1};
HashMap<Integer, Integer> test = new HashMap<Integer, Integer>();
for(int i = 0 ; i < nums.length ; ++i)
{
int complement = target-nums[i];
if(test.containsKey(complement))
{
return new int[]{test.get(complement), i};
}
else
{
test.put(nums[i], i);
}
}
return new int[]{-1, -1};
}
}
相关文章推荐
- Two Sum leetcode java
- LeetCode 1: Two Sum (JAVA)
- leetcode:Two Sum 【Java】
- Two Sum Leetcode Python Java
- [LeetCode][1]Two Sum解析 -Java实现
- 【Leetcode】two sum JAVA
- LeetCode 1 — Two Sum(C++ Java Python)
- Leetcode 第一题 Two Sum java代码
- [Leetcode] Two Sum (Java)
- [leetcode]leetcode第一题 1. Two Sum java O(n)解法
- Leetcode-1 Two Sum(Java) -by zzy
- 【LeetCode-面试算法经典-Java实现】【001-Two Sum(求两个数的和)】
- LeetCode(001) Two Sum (Java)
- LeetCode – Two Sum (Java) —题解
- LeetCode: Two Sum (Java)
- LeetCode java Two Sum
- LeetCode 001_Two Sum Java
- LeetCode 1 Two sum Java
- leetcode-Java-1. Two Sum.java
- LeetCode 1 - Two Sum ( JAVA )