Algorithm question: Given an array and a target number, find the sum of the two numbers in the array to be the target value, and print the two numbers. The time complexity is O(N)

Problem-solving ideas:

The first is loop traversal, let each element be added to the following element and then compared with the target value, and then output. The first layer of loop controls the currently compared element, and the second layer of loop controls the number of current comparisons. A double for loop is used here, and the time complexity is O(n^2), which does not meet the requirements. The code example is as follows

public static void main(String[] args) {
        int data[] = {2,7,9,10,12,15};
        int target = 14;
       //第一反应,循环遍历,一个一个相加进行比较
        for(int i=0;i<data.length;i++) {
            //每一个数需要比较几次
            for (int j=1+i;j<data.length;j++) {
                int total = data[i] + data[j];
                if (total == target) {
                    System.out.println("目标数:"+target+",Num1="+data[i]+",Num2="+data[j]);
                }
            }
        }
}

The second is to use Map instead of a layer of for loop to traverse the array elements, and use the map.containsKey method to determine whether there is a target value in the collection - the value of the current element. If it does not exist, use the element as the key, and the array subscript corresponding to the element Save it as a value in the map. If it exists, it means that it is found and output. This time complexity is O(n) to meet the requirements. The code is as follows

public static void main(String[] args) {
        int data[] = {2,7,9,10,12,15};
        int target = 14;
       
        //第二种,使用map结构代替一层for循环
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<data.length;i++) {
            //使用map来判断,判断map中是否含有
            if (map.containsKey(target-data[i])) {
                Integer integer1 = map.get(target - data[i]);
                System.out.println("目标数:"+target+",Num1="+data[integer1]+",Num2="+data[i]);
                break;
            }
            //没有就将值作为key,下标作为value放在map中
            map.put(data[i],i);

        }
    }

Note: In the future, if you encounter the situation of using double for loop to traverse to find elements, you can consider whether you can use map to replace one layer to reduce time complexity. Pro-test results: The execution time of the first type is between 40~88ms, and the execution time of the second type is between 1~5ms. Obviously, the execution efficiency of the second type is much faster!

Guess you like

Origin blog.csdn.net/guliudeng/article/details/130722205