算法经典问题--三数之和

算法经典问题--三数之和,第1张

算法经典问题--三数之和

下面是测试代码:

import java.util.HashMap;

public class TripleSum {
    public static void main(String[] args) {
    int[] test = {1,1,2,2,3,0,1};
    int goal = 4;
    tripleSum(test,goal);
    }
//散列算法
    public static void tripleSum(int[] array,int goal){
        HashMap map = new HashMap();
        HashMap map2 = new HashMap();

        for (int i = 1; i < array.length ; i++) {
            map.put(array[i],i);
        }
        for (int i = 0; i < array.length-1; i++) {
            int temp = goal - array[i];
            for (int j = i+2; j < array.length ; j++) {
                map2.put(array[j],j);
            }

            for(int j = i+1 ;jj){
                    System.out.println("["+i+","+j+","+map2.get(temp2)+"]");
                }
            }
        }
    }
}

结果:

Leetcode 要求输出的是去重复的Key的List

这个下次再说。 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5708123.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存