zoukankan      html  css  js  c++  java
  • LeetCode-300.Longst Increasing Subsequence

    Given an unsorted array of integers, find the length of longest increasing subsequence.

    Example:

    Input: [10,9,2,5,3,7,101,18]
    Output: 4 
    Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 

    Note:

    • There may be more than one LIS combination, it is only necessary for you to return the length.
    • Your algorithm should run in O(n2) complexity.

    Follow up: Could you improve it to O(n log n) time complexity?

    使用dp,时间复杂度为O(n2)

     1 public int lengthOfLIS(int[] nums) {//dp my
     2         if(null==nums||0==nums.length){
     3             return 0;
     4         }
     5         int max= 1;
     6         int[] re = new int[nums.length];//存放当前位置的最大长度
     7         re[0]=1;
     8         for(int i=1;i<nums.length;i++){
     9             re[i]=0;
    10             for(int j=i-1;j>=0;j--){
    11                 if(nums[j]<nums[i]&&re[i]<re[j]){//从当前位置往前,第一个比nums[i]小的值
    12                     re[i] = re[j];
    13                 }
    14             }
    15             re[i]++;
    16             if(re[i]>max){
    17                 max =re[i];
    18             }
    19         }
    20         return max;
    21     }

    利用二分,时间复杂度为O(nlogn)

    public int lengthOfLIS(int[] nums) {//二分 mytip
            if(null==nums||0==nums.length){
                return 0;
            }
            List<Integer> re = new ArrayList<>();//
            re.add(nums[0]);
            int index = 0;
            for(int i=1;i<nums.length;i++){
                if(nums[i]>re.get(re.size()-1)){//如果大于最后一个元素,直接插入
                    re.add(nums[i]);
                }
                else{
                    index = bs(0,re.size()-1,re,nums[i]);//二分找到第一个不大于nusm[i]的数的下标,然后替换为当前数
                    re.set(index,nums[i]);
                    
                }
            }
            return re.size();//数组长度为最大值
        }
        private int bs(int left,int right,List<Integer> list,int num){
            while(left<=right){
                if(left >= right){
                    return left;
                }
                else{
                    int mid = left + (right - left)/2;
                    if(list.get(mid)<num){
                        left = mid+1;
                    }
                    else{
                        right =mid;
                    }
                }
            }
            return left;
        }
  • 相关阅读:
    训练计划
    LA_3942 LA_4670 从字典树到AC自动机
    HDU 6180 Schedule
    HDU 6153 KMP
    HDU 2087 HDU 1867 KMP标准模板题
    Struts2学习8--文件上传(单个文件上传)
    SSH错误之--Error getting property descriptor: null at com.opensymphony.xwork2.ognl.accessor.XWorkCollectionPropertyAccessor.getProperty
    Struts2学习7---集合类型的类型转换
    工具-windows命令--查看端口占用情况,关闭端口
    Struts2学习6—OGNL (1)
  • 原文地址:https://www.cnblogs.com/zhacai/p/10661330.html
Copyright © 2011-2022 走看看