输入一串数字,找到其中两个数的和为某个给定值的坐标

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/c15158032319/article/details/84850409
  • 题目: 输入一串数字,找到其中两个数的和为某个给定值的坐标

  • 例子:输入一串数字如 2,8,6,7,3;找到其中两个数的和加起来等于9的坐标;显然2+7=8,那么结果为0,3

解法一:
    int result = 9;
    public void findIndex(int... arr){
        for(int i = 0;i<arr.length;i++){
            for(int j=i;j<arr.length;j++){
                if(arr[i] + arr[j] == result){
                    System.out.println(i);
                    System.out.println(j);
                    return;
                }
            }
        }
    }

显然上述代码在最坏的遍历情况下,时间复杂度接近于O(n2)了,这个肯定不是最好的解法。我们不妨换位思考一下,既然是求2+7=9的情况,那么是不是也可以换做求9-2=7的情况呢。只要当我们遍历一个数num的时候,只要知道前面是否存在一个数9-num的值不就可以了吗,很显然,map最适合帮忙搞定了。这样即使最坏的情况只要遍历一遍这串数字就可以得出结果了,时间复杂度不大于O(n)。

解法二:
    int result = 9;
    public void findIndex(int... arr){
        Map<Integer,Integer> map = new HashMap();
        for(int i = 0;i<arr.length;i++){
            map.put(arr[i],i);
            if(map.get(result - arr[i])!= null){
                System.out.println(map.get(result - arr[i]));
                System.out.println(i);
                return;
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/c15158032319/article/details/84850409