LeetCode—300 Longest Increasing Subsequence
2015-11-06 14:24
549 查看
思路:遍历数组,建立另外一个数组维护,维护规则,每次读到的数跟这个数组有效距离最后一个数比较,如果比最后一个数大(或者该数组为空)则插入这个数,并使得有效长度+1;如果小于最后一个数,则在这个数组中找到第一个比自己大的数替换掉,如果发现这个数组中有跟自己相同的数,那么就不操作这个数。因为是有序数组,所以插入的时间复杂度为O(lgn);
public class Solution {
int[] ans;
int length=0;
public int lengthOfLIS(int[] nums) {
ans=new int[nums.length];
for (int i = 0; i < nums.length; i++) {
f(nums[i]);
}
return length;
}
public void f(int n){
if (length==0||ans[length-1]<n) {
ans[length]=n;
length++;
}else {
int s=0;
int e=length-1;
int m=(s+e)/2;
while (e-s>1) {
if(ans[m]==n){
return;
}
if (ans[m]>n) {
e=m;
}else {
s=m;
}
m=(s+e)/2;
}
if (ans[s]>n) {
ans[s]=n;
}else {
ans[e]=n;
}
}
}
}
public class Solution {
int[] ans;
int length=0;
public int lengthOfLIS(int[] nums) {
ans=new int[nums.length];
for (int i = 0; i < nums.length; i++) {
f(nums[i]);
}
return length;
}
public void f(int n){
if (length==0||ans[length-1]<n) {
ans[length]=n;
length++;
}else {
int s=0;
int e=length-1;
int m=(s+e)/2;
while (e-s>1) {
if(ans[m]==n){
return;
}
if (ans[m]>n) {
e=m;
}else {
s=m;
}
m=(s+e)/2;
}
if (ans[s]>n) {
ans[s]=n;
}else {
ans[e]=n;
}
}
}
}
相关文章推荐
- 给定["a","b","a","b","c","a","b","c","b"]字符串数组,然后使用Map的key来保存数组的字符串元素,value保存该字符串元素出现的次数。
- UILabell自动调整宽度width
- Win10 build 10586预览版升级失败卡在40%该怎么办?
- 本文对UITabBarController进行分析,研究苹果内部是怎么构造出这个类的,以及我们怎么去自定义一个类
- atmega32u4制作arduino leonardo最小系统
- Android消息机制:Looper、Handler、MessageQueue分析
- Your build settings specify a provisioning profile with the UUID “”, however, no such provisioning profile was found
- [桌面版] 在 Mockplus 2.1 (预览版)中使用图片轮播
- [桌面版] 在 Mockplus 2.1 (预览版)中使用母版
- 将easyui 的自带分页组件修改为中文
- leetcode 300 : Longest Increasing Subsequence
- IOS9 UItableView 拖动卡顿明显
- UESTC 1218(DP)
- UITableView 点击背景色
- java GUI简单记事本
- mysql depended_query 优化案例一则
- UITableView分隔线间距为0
- iOS中设计一个Block代码执行的UIAlertView
- iOS中UITableViewController自带的刷新控件
- DroidDraw UI设计软件开发Android GUI应用程序