The sum of two Numbers
1、n*(n-1)/2 Method to iterate through,Call each other Time complexity:O(n^2) Spatial complexityO(1)
class Solution {
public int[] twoSum(int[] nums, int target) {
int s = nums.length - 1;
for (int i = 0; i < s ; i++) {
for (int j = i+1; j < nums.length; j++) {
if (target == nums[i] + nums[j]) {
return new int[] {i , j};
}
}
}
throw new IllegalArgumentException("no solution");
}
}
2、The hash table holds all the information,Time complexityO(n)Spatial complexityO(n)
// 定义一个hash表
HashMap<Integer, Integer> map = new HashMap();
// 1. 遍历数组,将数据全部保存入hash表
for (int i = 0, l = nums.length; i < l ; i++){
map.put(nums[i], i);
}
// 2. 再次遍历数组,寻找每个数对应的那个数是否存在
for (int i = 0, l = nums.length; i < l ; i++) {
int thatNum = target - nums[i];
// 如果那个数存在,并且不是当前数自身,就直接返回结果
if (map.containsKey(thatNum) && map.get(thatNum) != i) {
return new int[] {i, map.get(thatNum)};
}
}
throw new IllegalArgumentException("no solution");
3、A traversal , Time complexityO(n)Spatial complexityO(n) faster
// 定义一个hash表
HashMap<Integer, Integer> map = new HashMap();
// 1. 遍历数组,将数据全部保存入hash表
for (int i = 0, l = nums.length; i < l ; i++){
int thatNum = target - nums[i];
if (map.containsKey(thatNum) && map.get(thatNum) != i) {
return new int[] {map.get(thatNum),i};
}
map.put(nums[i], i); //O(1)
}
throw new IllegalArgumentException("no solution");
If you want to calculate time ,This can be done in the following ways
The sum of three number
Double pointer
package ThreeNumbers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThreeWay {
public static void main(String[] args) {
int[] nums = {0,0,0};
System.out.println(gather(nums));
}
public static List<List<Integer>> gather(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> bigList = new ArrayList<List<Integer>>();
int numsLength = nums.length;
for (int i = 0 , l = numsLength; i < l; i++ ) {
int j = i + 1;
int k = l - 1;
if (nums[i] > 0) {
break;
}
if (i > 0 && nums[i - 1] == nums[i]) {
continue;
}
while (j < k) {
int thatNum = nums[i] + nums[j] + nums[k];
if (thatNum == 0) {
bigList.add(Arrays.asList(nums[i], nums[j], nums[k]));
j++;
k--;
while (j < k && nums[j-1] == nums[j]) j++;
while (j < k && nums[k+1] == nums[k]) k--;
}else if (thatNum < 0) {
j++;
}else if (thatNum > 0) {
k--;
}
}
}
return bigList;
}
}