algorithm@ O(3/2 n) time to findmaximum and minimum in a array

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了algorithm@ O(3/2 n) time to findmaximum and minimum in a array相关的知识,希望对你有一定的参考价值。

    public static int[] max_min(int[] a){
        //res[0] records the minimum value while res[1] records the maximal one.
        int res[] = new int[2];
        int n = a.length;
        if(n == 0)  {
            return res;
        }
        if(n == 1) {
            res[0] = res[1] = a[0];
        }
        
        int min, max;
        if(n%2 == 1) {
            res[0] = res[1] = a[0];
            
            for(int i=1; i<=n-2; i+=2) {
                if(a[i] < a[i+1]) {
                    min = a[i];
                    max = a[i+1];
                }
                else {
                    min = a[i+1];
                    max = a[i];
                }
                res[0] = Math.min(min, res[0]);
                res[1] = Math.max(max, res[1]);
            }
        }
        else {
            res[0] = Math.min(a[0], a[1]);
            res[1] = Math.max(a[0], a[1]);
            for(int i=2; i<=n-2; i+=2) {
                if(a[i] < a[i+1]) {
                    min = a[i];
                    max = a[i+1];
                }
                else {
                    min = a[i+1];
                    max = a[i];
                }
                res[0] = Math.min(min, res[0]);
                res[1] = Math.max(max, res[1]);
            }
        }
        
        return res;
    }

 

以上是关于algorithm@ O(3/2 n) time to findmaximum and minimum in a array的主要内容,如果未能解决你的问题,请参考以下文章

Mit Algorithm 2

LeetCode 229 Majority Element II(主要元素II)(Array)(Boyer–Moore majority vote algorithm)

[LC] 46. Permutations

Strassen algorithm(O(n^lg7))

LeetCode 144: Binary Tree Preorder Traversal

LeetCode 145: Binary Tree Postorder Traversal