zoukankan      html  css  js  c++  java
  • 算法总结之 需要排序的最短子数长度

    给定一个无序数组arr,求出需要排序的最短子数组长度

    例如: arr=[1,5,3,4,2,6,7] 返回4,因为只有[5,3,4,2]需要排序

    介绍一种 左右遍历方法   左右夹击 确认长度

    首先从 右往左遍历 记录最小值 如果arr[i] >最小值  那么 最小值的位置应该在arr[i]的左边

    然后从 左往右遍历  类似的思想不在累述

    package TT;
    
    public class Test17 {
    
       public static int getMinLength(int[] arr){
           
           if(arr==null || arr.length<2){
               return 0;
           }
           int min = arr[arr.length-1];
           int noMinIndex = -1;   //记录位置
           for(int i= arr.length-2; i !=-1; i--){
               if(arr[i]>min){
                   noMinIndex=i;
               }else {
                min=Math.min(min,arr[i]);
            }
           }
           if(noMinIndex == -1){
               return 0;
           }   
           int max=arr[0];
           int noMaxIndex=-1;
           for(int i =1; i!=arr.length; i++){
                 if(arr[i]<max){
                     noMaxIndex=i;
                 }else {
                    max=Math.max(max,arr[i]);
                }
           }
        return noMaxIndex - noMinIndex +1;          
       }
       public static void main(String[] args){
           int[] a = new int[7];
          a[0]=1;
          a[1]=5;
          a[2]=3;
          a[3]=4;
          a[4]=2;
          a[5]=6;
          a[6]=7;      
          int c = getMinLength(a);      
          System.out.println(c);
       }
       
    }

    测试结果:

    public class Test7 {
       public  static int  getNeedSortLen(int[] arr){
           int right = arr.length-1;
           int left = 0;
               while (left<=right && arr[left]<arr[left+1]){
                   left++;
               }
               while (right >=0 && arr[right]>arr[right-1]){
                   right--;
               }
           return right-left+1;
       }
        public static void main(String[] args) {
             int[] arr = {1,5,3,4,2,6,};
            System.out.println( getNeedSortLen(arr));
        }
    }
  • 相关阅读:
    Codeforces 1265A Beautiful String
    1039 Course List for Student (25)
    1038 Recover the Smallest Number (30)
    1037 Magic Coupon (25)
    1024 Palindromic Number (25)
    1051 Pop Sequence (25)
    1019 General Palindromic Number (20)
    1031 Hello World for U (20)
    1012 The Best Rank (25)
    1011 World Cup Betting (20)
  • 原文地址:https://www.cnblogs.com/toov5/p/7435842.html
Copyright © 2011-2022 走看看