A tool for calculating the big-O time complexity of Java code?

后端 未结 2 2056
别那么骄傲
别那么骄傲 2020-12-05 18:45

I have a question regarding time complexity (big O notation) for Java software. Is there a way to quickly calculate or test it (or any website that could calculate it for m

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 19:42

    I might be solving someone's homework, but the question was begging for a sane solution...

    Counting distinct digits in a number requires no strings, sets or regular expressions, just some simple arithmetics.

    The following method runs in O(n) time (n = number of digits in the input) and constant space:

    int distinctDigits(int num) {
      if (num == 0) {
        return 1;
      }
    
      boolean[] digits = new boolean[10];
    
      while (num > 0) {
        digits[num % 10] = true;
        num /= 10;
      }
    
      int count = 0;
      for (boolean digit : digits) {
        if (digit) {
          count++;
        }
      }
    
      return count;
    }
    

    Making this work for negative numbers is left as an exericse to the reader ;)

提交回复
热议问题