Leetcode 1. Two Sum (java),leetcodesum
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].
解法一:
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 ){
int[] result = new int[2];
result[0] = i;
result[1] = j;
return result;
}
}
}
return null;
}
}
使用了兩層迴圈進行遍曆,時間複雜度為O(n²)
解法二:
class Solution {
public int[] twoSum(int[] nums, int target) {
Hashtable<Integer,Integer> map = new Hashtable<Integer,Integer>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i],i);
}
for (int i = 0; i < nums.length; i++) {
int another = target - nums[i];
//過濾元素本身
if( map.get(another) != null &&map.get(another) > i ){
int[] result = new int[2];
result[0] = i;
result[1] = map.get(another);
return result;
}
}
return null;
}
}
使用了雜湊表進行尋找,時間複雜度為O(n)
解法一使用的是順序尋找,時間複雜度為O(n)
解法二使用的是雜湊尋找,時間複雜度為O(1)
此外常用的尋找:二分尋找O(logn),二叉排序尋找法O(logn),分塊尋找O(logn)
github地址:https://github.com/CyanChan/Leetcode-Record