๐ ๐ ๐ ๐ 300. ๆ้ฟ้ๅขๅญๅบๅ
2022ๅนด6ๆ9ๆฅๅคง็บฆ 1 ๅ้
๐ ๐ ๐ ๐ 300. ๆ้ฟ้ๅขๅญๅบๅ
้พๅบฆ: ๐ ๐ ๐ ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ 1 - dp
class Solution {
public int lengthOfLIS(int[] nums) {
// ๆ่ทฏ๏ผ
// dp[i] = max{dp[j] + 1}, j < [0, i)
// ไปฅ i ไธบๆซๅฐพไธๆ ็ๆ้ฟ้ๅขๅญๅบๅ้ฟๅบฆ
int len = nums.length;
int[] dp = new int[len];
// ๅๅงๅ
Arrays.fill(dp, 1);
int res = 1;
// dp
for(int i = 1; i < len; i ++) {
for(int j = 0; j < i; j ++) {
if(nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
res = Math.max(res, dp[i]);
}
}
}
return res;
}
}
่พๅบ
่งฃๆณ2 - ไบๅ
class Solution {
public int lengthOfLIS(int[] nums) {
// ๆ่ทฏ๏ผ
// ๅ็ - ไบๅๅ ้ๆฅๆพ็็ๆๅ
ฅไฝ็ฝฎ
int count = 0;
int len = nums.length;
int[] array = new int[len]; // ๆๅค len ไธช็ๅ ๏ผๅณๅ
จ้จๅ
็ด ๅฝขๆ้ๅขๅญๅบๅ
array[0] = nums[0];
count ++; // ๅๅงๆไธไธช็ๅ
// ไพๆฌกๆทปๅ ๆฐ็ๅฐ็ๅ ไธญ
for(int i = 1; i < len; i ++) {
// ็นๆฎๆ
ๅต็นๅค
if(nums[i] > array[count - 1]) {
array[count] = nums[i];
count ++;
continue;
}
if(nums[i] <= array[0]) {
array[0] = nums[i];
continue;
}
// ไบๅ็กฎๅฎๆๅ
ฅไฝ็ฝฎ
int index = getIndex(array, 0, count - 1, nums[i]);
array[index] = nums[i];
}
return count;
}
private int getIndex(int[] array, int left, int right, int target) {
// ้ๅฝ็ปๆญขๆกไปถ
if(left >= right) {
return left;
}
if(target <= array[left]) {
return left;
}
int mid = left + ((right - left) >> 1);
if(array[mid] == target) {
return mid;
} else if(target > array[mid]) {
return getIndex(array, mid + 1, right, target);
} else {
// target < mid
return getIndex(array, left, mid, target);
}
}
}