两数相加

master
alis-lc 1 year ago
parent 86f126a372
commit 4aae3ec3f1

@ -0,0 +1,106 @@
package org.alis.algorithm.leetcode;
import java.util.HashMap;
import java.util.Map;
/**
*
*
*
* @author lc
* @date 2023/10/28 14:32
*/
public class LeetCode18 {
private final int[] ints = {3, 2, 1, 4};
private final int target = 6;
public void exec() {
// 基础版本
for (int i = 0; i < ints.length; i++) {
for (int j = 0; j < ints.length; j++) {
if (target == ints[j] + ints[i]) {
System.out.println("target 下标 是 " + i + ":" + j);
}
}
}
}
public int[] half(int[] array, int ta) {
int courseOne = array.length / 2;
// 先获取目标一半的数据
int addOne = array[courseOne];
while (true) {
// 开始走计算
if (addOne <= ta) {
int i = ta - addOne;
int search;
if (i > addOne) {
// 向上找
search = search(i, array, courseOne, array.length);
} else {
// 向下找
search = search(i, array, 0, courseOne);
}
if (search > -1 && search != courseOne) {
return new int[]{courseOne, search};
}
}
if (courseOne == 0) {
courseOne = array.length - 1;
} else {
courseOne = courseOne / 2;
}
addOne = array[courseOne];
}
}
private int search(int i, int[] array, int start, int end) {
int left = start;
int right = end;
while (left <= right) { // 注意
int mid = (right + left) / 2;
// 避免边际查询
if (mid < 0 || mid >= array.length) {
return -1;
}
if (array[mid] == i)
return mid;
else if (array[mid] < i)
left = mid + 1; // 注意
else if (array[mid] > i)
right = mid - 1; // 注意
}
return -1;
}
public int[] hash() {
Map<Integer, Integer> map = new HashMap<>();
// hashMap
for (int i = 0; i < ints.length; i++) {
int two = target - ints[i];
if (map.containsKey(two)) {
return new int[]{map.get(two), i};
}
map.put(ints[i], i);
}
return new int[]{};
}
public static void main(String[] args) {
LetCode letCode = new LetCode();
letCode.hash();
}
}
Loading…
Cancel
Save