三数之和

给定一个数组或输入一个数组,在数组里取三个数使这三个数等于一个特定的值target,并返回这三个数的下标,要求不能有重复的组合。

java 复制代码
package 例题;

import java.util.HashMap;
//三数之和
public class Test1 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 5, 7, 9, 11, 13, 16, 14, 15,18, 94, 42, 35};
        int target = 40;//三数之和
        HashMap<Integer, Integer> map = new HashMap<>();
        HashMap<Integer, Integer> map2 = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            map.put(arr[i], i);
        }
        for (int i = 0; i < arr.length; i++) {
            int w =target-arr[i];
            int[] xx = get(arr,w);
            if(xx[0]!=-1){
                if(i!=xx[0]&&i!=xx[1]){
                    if(map2.get(i)==null||map2.get(xx[0])==null){
                        map2.put(i,i);
                        map2.put(xx[0],xx[0]);
                        map2.put(xx[1],xx[1]);
                        System.out.println("位置:"+i+","+xx[0]+","+xx[1]);
                    }
                }
            }
        }
    }
    public static int[] get(int[] arr,int target){
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            map.put(arr[i], i);
        }
        for (int i = 0; i < arr.length; i++) {
            int w = target - arr[i];
            Integer index = map.get(w);
            if (index != null) {
                return new int[]{i, index};
            }
        }
        return new int[]{-1,-1};
    }

}
相关推荐
Gorway4 小时前
解析残差网络 (ResNet)
算法
拖拉斯旋风4 小时前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用
算法
Wect4 小时前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript
灵感__idea18 小时前
Hello 算法:众里寻她千“百度”
前端·javascript·算法
Wect1 天前
LeetCode 130. 被围绕的区域:两种解法详解(BFS/DFS)
前端·算法·typescript
NAGNIP2 天前
一文搞懂深度学习中的通用逼近定理!
人工智能·算法·面试
颜酱2 天前
单调栈:从模板到实战
javascript·后端·算法
CoovallyAIHub2 天前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉
CoovallyAIHub2 天前
从春晚机器人到零样本革命:YOLO26-Pose姿态估计实战指南
深度学习·算法·计算机视觉
CoovallyAIHub2 天前
Le-DETR:省80%预训练数据,这个实时检测Transformer刷新SOTA|Georgia Tech & 北交大
深度学习·算法·计算机视觉