diff --git a/datastructure/src/main/java/org/alis/algorithm/leetcode/LeetCode18.java b/datastructure/src/main/java/org/alis/algorithm/leetcode/LeetCode18.java new file mode 100644 index 0000000..c1648fe --- /dev/null +++ b/datastructure/src/main/java/org/alis/algorithm/leetcode/LeetCode18.java @@ -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 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(); + } + + + + + +}