zoukankan      html  css  js  c++  java
  • 有序数组排序

    问题:

    给定一个数组,其值先从小到大递增后从大到小递减,找出最大的值。

    思路:最简单的办法就是从第二个值开始,判断是否满足 A[i] > A[i-1] && A[i] > A[i+1]. 如果满足,i 就是那个最大值的下标。该算法复杂度为O(n).

    我们可以改进这种算法,因为这个数组是排好序的,所以我们可以利用二分查找的思想,更快速的找到最大值,时间复杂度为O(lg n)。

    二分查找的算法可以在后面的link处得到,二分查找的退出条件和这道题的退出条件是不一样的(详见while loop),这是很值得注意的地方。

    http://blog.csdn.net/beiyeqingteng/article/details/5736004

    [java] view plain copy
     
    1. public int turningPoint(int[] A) {  
    2.         int m = A.length;  
    3.         int begin = 0;        
    4.         int end = m - 1;          
    5.         int tp = begin + (end - begin)/2;  
    6.           
    7.         // the condition "tp > 0 && tp < m -1" makes sure that tp is not at the beginning or the end  
    8.         while (tp > 0 && tp < m -1) {           
    9.             if (A[tp] > A[tp + 1] && A[tp] > A[tp -1]) {  
    10.                 return tp;  
    11.             } else if (A[tp] < A[tp+1]) {  
    12.                 begin = tp + 1;  
    13.                 tp = begin + (end - begin)/2;  
    14.             } else {  
    15.                 end = tp - 1;  
    16.                 tp = begin + (end - begin)/2;  
    17.             }             
    18.         }  
    19.           
    20.         return -1;  
    21.     }  
  • 相关阅读:
    CF732 F Tourist Reform——边双连通分量
    CF36 E Two Paths——欧拉(回)路
    最小生成树()
    Bellman-Ford算法
    SPFA算法
    归并排序(Merge_Sort)
    并查集
    int(3)与int(11)的区别
    mysql应该看的blog
    mysql建立索引
  • 原文地址:https://www.cnblogs.com/xiaohuamao/p/6940065.html
Copyright © 2011-2022 走看看