Leetcode 300) Longest Increasing Subsequence

image

내 답안

class Solution {
    public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length];

        for(int i=0;i<nums.length;i++){
            dp[i]=1;
            for(int j=0;j<i;j++){
                if(nums[i] > nums[j]){
                    dp[i]=Math.max(dp[j]+1,dp[i]);
                }
            }
        }
        int max=0;
        for(int i:dp){
            max= Math.max(max,i);
        }
        return max;

    }
} 

다른 답안

  • 이진 탐색으로 사용해서
class Solution {
    public int lengthOfLIS(int[] nums) {
        int n = nums.length;
        if(nums.length==1) return 1;
        int[] tail = new int[n];
        int size =0;
        for(int num : nums) {
            int i =0, j = size;
            while(i<j) {
                int mid = i + (j-i)/2;
                if(tail[mid] < num) i = mid+1;
                else if(tail[mid] > num) j = mid;
                else j = mid;
            }
            tail[i] = num;
            if(i==size) size++;
        }
        return size;
    }

© 2018. All rights reserved.

Powered by Hydejack v8.5.2