三数之和

给定一个数组或输入一个数组,在数组里取三个数使这三个数等于一个特定的值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};
    }

}
相关推荐
青山是哪个青山4 分钟前
LeetCode 188:买卖股票的最佳时机 IV
算法
a1879272183124 分钟前
【算法】树(二):队列与祖先——BFS 骨架三配件、短路透传与合流
算法·leetcode·二叉树··bfs·算法讲解·树遍历
syagain_zsx1 小时前
算法基础篇 · 03 枚举(C++ 题解)
c++·算法·二进制·枚举
weixin_307779131 小时前
C++代码实现MATLAB中的ode23tb函数功能
开发语言·c++·算法·matlab
我是章汕呐2 小时前
地级市能源消耗量及消耗强度数据【2006-2023年】平衡面板
人工智能·经验分享·算法·回归
charliejohn2 小时前
计算机考研 408 数据结构 堆的插入与删除 堆排序
算法
老鱼说AI3 小时前
从点积到希尔伯特空间:向量内积的几何本质与大模型相似度度量
人工智能·深度学习·线性代数·算法·机器学习·数学建模
地平线开发者3 小时前
模型部署|如何解决算子约束
深度学习·算法·自动驾驶
Navigator_Z4 小时前
LeetCode //C - 1254. Number of Closed Islands
c语言·算法·leetcode
deepseek234 小时前
GPT-6 Astra 破解 FrontierMath 九年悬案拆解:调和熵投票规则反证核恒非空,局部搜索如何终结反例悬赏
人工智能·算法·ai agent