简体   繁体   English

面试时问的时间复杂度问题

[英]Time complexity question asked in interview

int[] a = {3,5,4,3,2,2,1};

        System.out.println("Duplicate elements are: ");

        for(int i=0; i<a.length; i++) {
            for(int j = i+1; j<a.length; j++) {
                if(a[i]==a[j]  && i!=j){
                    System.out.println(a[j] + " ");
                }
            }
        }

This codes time complexity is O(n^2), interviewer asked me to change it to O(n).这段代码时间复杂度是O(n^2),面试官让我改成O(n)。 How can we do that?我们怎么做?

This is one solution which would meet the O(n) requirement, that would be to use a HashSet - A HashSet will not accept a duplicate value, so one loop is all you need, that is if the requirements allow for use of a declared HashSet :这是一种满足O(n)要求的解决方案,即使用HashSet - HashSet不接受重复值,因此您只需要一个循环,即如果要求允许使用声明的HashSet

int[] a = {3,5,4,3,2,2,1};
// Create a set 
Set<Integer> set = new HashSet<Integer>();
//Create a set for storing duplicates
Set<Integer> setDupes = new HashSet<Integer>();

System.out.println("Duplicate elements are: ");

//loop the array once 
for (int num : a) 
{ 
     if (set.add(num) == false) 
     { 
        // your duplicate element
        if(setDupes.add(num) == true) 
           System.out.println(num + " ");
     } 
}

It depends on what you want to do inside the loop.这取决于你想在循环内做什么。 If they are not dependent then you can merge both of them in one如果它们不依赖,那么您可以将它们合二为一

When the loops are not dependent you can re-write the loop as:当循环不依赖时,您可以将循环重写为:

    for (int i = 0, j=0; i < n && j<n; i++;j++) {
        //do something in constant time
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM