运行时间复杂度分析

huangapple go评论103阅读模式
英文:

Analysis of run time complexity

问题

  1. /**
  2. *mostOften方法
  3. *@param array 数组[],整数n
  4. */
  5. static int mostOften(int array[], int n){
  6. // 将数组升序排序
  7. Arrays.sort(array);
  8. // 计算数组中的最大出现次数
  9. int maxO = 1;
  10. // 跟踪数组中的整数
  11. int result = array[0];
  12. // 计数变量
  13. int count = 1;
  14. /**
  15. * 循环按线性方式遍历数组,并比较索引i处和索引i-1处的元素。
  16. * 根据可能的每种情况递增count和maxO。
  17. */
  18. for(int i = 1; i < n; i++){
  19. // 如果整数相同,则递增count。
  20. if (array[i] == array[i - 1]){
  21. count++;
  22. }//关闭if语句
  23. // 否则,如果整数不同
  24. else{
  25. // 如果count大于maxO,则该整数具有更高的出现次数
  26. if (count > maxO){
  27. // count现在变为maxO
  28. maxO = count;
  29. // 用具有最高出现次数的整数替换result。
  30. result = array[i - 1];
  31. }//关闭if语句
  32. // 将count重置为1。
  33. count = 1;
  34. }//关闭else语句
  35. }//关闭for循环
  36. //@返回int数据类型
  37. return result;
  38. }//关闭mostOften方法
英文:

I need some help below I have some code I created for an assignment. I am having a hard time figuring out the time complexity of this algorithm. I looked at it and believe the O-notation is 0(n) and the function is F(n)= 4 + 2n. But I think that is incorrect.

  1. /**
  2. *mostOften method
  3. *@param receives Array[] , int
  4. */
  5. static int mostOften(int array[] , int n){
  6. //Array to be sorted in ascending order
  7. Arrays.sort(array);
  8. //counts number of max occurrences in the array
  9. int maxO = 1;
  10. //Keeps track of the integer at Array[i].
  11. int result = array[0];
  12. //variable to count occurrences
  13. int count = 1;
  14. /**
  15. *loop passes through array in linear motion and compares index at i and index at
  16. * i - 1. For every possible outcome count and maxO are incremented accordingly.
  17. */
  18. for(int i = 1 ; i &lt; n ; i++){
  19. //If integers are the same increment count.
  20. if (array[i] == array[i - 1]){
  21. count++;
  22. }//close if statement
  23. // else if integers are not the same
  24. else{
  25. //if count is larger thatn maxO that integer is the highers occurrence
  26. if (count &gt; maxO){
  27. //count is now maxO
  28. maxO = count;
  29. //replaces result with integers with highest occurrence.
  30. result = array[i - 1];
  31. }//close if statement
  32. //reset count to 1.
  33. count = 1;
  34. }//close else statement
  35. }//close for loop
  36. //@returns int data type
  37. return result;
  38. }//close mostOften method

答案1

得分: 2

只想指出Arrays.sort本身的时间复杂度是O(n logn)。
如果我们忽略这一点,循环所需时间是线性的。

英文:

Just wanted to point out that Arrays.sort itself is O(n logn).
If we ignore that, the loop takes linear time.

huangapple
  • 本文由 发表于 2020年9月9日 08:50:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63803302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定