有序数组中任意两个数的和为指定数值

1:将数组中的元素存储在hashmap中,其中key为数组的元素,value为其在数组的下标
2:遍历整个hashmap, 如果hashmap的key中包括(total - curNum),那么说明数组中存在另外一个数满足和当前数相加为total的元素

package com;

import jdk.internal.org.objectweb.asm.Handle;

import java.util.HashMap;

public class shu {
    public static void main(String[] args) {
        int[] array={2,3,4,6,7,8,9};
        int total=10;
        TwoS(array,total);
    }
    public static void TwoS(int[] array,int total) {
        if (array==null||array.length<=1)
            return ;
        HashMap<Integer,Integer> hashMap=new HashMap<>();//组合数的下标
        HashMap<Integer,Integer> valuehashmap=new HashMap<>();//已遍历过的数据
        int temp=0;
        for (int i = 0; i < array.length; i++) {
            temp=total-array[i];
            if (valuehashmap.containsKey(temp)){
                hashMap.put(valuehashmap.get(temp),i);
                continue;
            }
            valuehashmap.put(array[i],i);
        }
        valuehashmap=null;
        for (int key:hashMap.keySet()){
            System.out.println(array[key]+"  "+array[hashMap.get(key)]);
        }
    }
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值