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

2021-05-09  本文已影响0人  android_coder

1:找到其中的一组

将数组中的所有的值放入HashMap的Key中,Value存放该值对应的下标,遍历这个HashMap,取得Key,计算如果可以和这个Key加起来的和为num的值,如果这个值存在,就直接返回这两个下标。遍历一次的时间复杂度为O(N),查找的时间复杂度是O(1),总体时间复杂度O(N)。

  private static void findTwoTotalNumber(int[] array, int number) {
        if (array == null || array.length <= 1) {
            return;
        }
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        int index = 0;
        for (int num: array) {
            hashMap.put(num, index++);
        }
        for (Integer num: hashMap.keySet()) {
            if (hashMap.containsKey(number - num)) {
                System.out.println("one is;" + num +"--index==" + hashMap.get(num) +"--other is:"
                        + (number - num) + "--index is ==" + hashMap.get(number - num));
                return;
            }
        }
    }

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

问题:
上面的做法只能找到一组满足条件的组合,实际情况是可能有多组,那么我们看下多组的实现方式

2:找到满足所有的组合

 private static void findTwoNumberTotal(int[] array, int total) {
        if (array == null || array.length <= 1) {
            return;
        }
        /* 组合数的下标,key和value */
        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)) {------>如果包含另外一个组合数
              //valueHashMap.get(temp)得到的是另外一个组合数的下标
              //hashmap存储的是两个组合数的下标
               hashMap.put(valueHashMap.get(temp), i);
               continue;
           }
            valueHashMap.put(array[i], i);------>将数组的元素按照值和在数组对应的下标存储
        }
        valueHashMap = null;
        for (int key : hashMap.keySet()) {
           //因为hashmap的key是一个组合数的下标,value是另外一个组合数的下标
            System.out.println(array[key] + " " + array[hashMap.get(key)]);
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读