#1 Two Sum 兩數之和
just for the record, not the best solutions.
if you like to study together, my discord: Journey#9805

package com.journey;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class TowSum_兩數之和_001 {
//hash
public static int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[1] = i;
result[0] = map.get(target - nums[i]);
return result;
}
map.put(nums[i], i);
}
return result;
}
//sort + 2 pointers
public static int[] twoSumSolution2(int[] nums, int target) {
int m = 0, n = 0, k, board = 0;
int len = nums.length;
int[] result = new int[2];
int[] temp1 = new int[len];
System.arraycopy(nums, 0, temp1, 0, len);
Arrays.sort(nums);
for (int i = 0, j = len - 1; i < j; ) {
//數組排序後, i = 頭; j = 尾,如果i+j小於target,i後移1位
if (nums[i] + nums[j] < target) {
i++;
} else if (nums[i] + nums[j] == target) {
m = i;
n = j;
break;
}
}
for (k = 0; k < len; k++) {
if (temp1[k] == nums[m]) { //對比
result[0] = k;
break;
}
}
for (int i = 0; i < len; i++) {
if (temp1[i] == nums[n] && i != k) {
result[1] = i;
}
}
return result;
}
//for
public static int[] twoSumSolution3(int[] nums, int target) {
int[] result = new int[2];
int len = nums.length;
int i, j;
for (i = 0; i < len; i++) {
for (j = i + 1; j < len; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
public static void main(String[] args) {
int[] test1 = new int[]{7, 0, 3, 1, 2, 3, 4, 5, 6};
int targetTest1 = 10;
twoSum(test1,targetTest1); // 0 2
twoSumSolution2(test1,targetTest1); // 2 0
twoSumSolution3(test1,targetTest1); // 0 2
}
}
😚