在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: Note:
Follow up: Could you improve it to O(n log n) time complexity? 给定一个无序的整数数组,找到其中最长上升子序列的长度。 示例: 输入: 说明:
进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗? 16ms 1 class Solution { 2 func lengthOfLIS(_ nums: [Int]) -> Int { 3 if nums.count < 2 { 4 return nums.count 5 } 6 var res = Array(repeating: 0, count: nums.count) 7 res[0] = nums[0] 8 var count = 1 9 var j = 0 10 for i in 0..<nums.count { 11 let tmp = nums[i] 12 if tmp > res[count - 1] { 13 j = count 14 count += 1 15 }else { 16 var left = 0 17 var right = count - 1 18 while left < right { 19 let mid = (left + right) / 2 20 if res[mid] >= nums[i] { 21 right = mid 22 }else { 23 left = mid + 1 24 } 25 } 26 j = left 27 } 28 res[j] = nums[i] 29 } 30 return count 31 } 32 } 56ms 1 class Solution { 2 func lengthOfLIS(_ nums: [Int]) -> Int { 3 var results = [Int]() 4 for num in nums { 5 var needAdd = true 6 if results.count > 0 { 7 for index in 0..<results.count { 8 if num <= results[index] { 9 results[index] = num 10 needAdd = false 11 break 12 } 13 } 14 } 15 if needAdd { 16 results.append(num) 17 } 18 } 19 return results.count 20 } 21 } 300ms 1 class Solution { 2 func lengthOfLIS(_ nums: [Int]) -> Int { 3 guard !nums.isEmpty else { 4 return 0 5 } 6 7 var dps = Array(repeating: 1, count: nums.count) 8 var result = 1 9 for index in 1..<nums.count { 10 let num = nums[index] 11 for j in 0..<index { 12 if num > nums[j] { 13 let length = dps[j] + 1 14 if length > dps[index] { 15 dps[index] = length 16 result = max(result, dps[index]) 17 } 18 } 19 } 20 } 21 22 return result 23 } 24 } 312ms 1 class Solution { 2 func lengthOfLIS(_ nums: [Int]) -> Int { 3 var length_global = 0 4 var length_current = [Int].init(repeating:1 , count: nums.count) 5 6 for i in 0..<nums.count { 7 for j in 0..<i { 8 if nums[i] > nums[j] { 9 length_current[i] = max(length_current[i], length_current[j] + 1) 10 } 11 } 12 length_global = max(length_global, length_current[i]) 13 } 14 15 return length_global 16 } 17 } 376ms 1 class Solution { 2 func lengthOfLIS(_ nums: [Int]) -> Int { 3 guard !nums.isEmpty else { 4 return 0 5 } 6 7 var dps = Array(repeating: 1, count: nums.count) 8 var result = 1 9 for index in 1..<nums.count { 10 let num = nums[index] 11 for j in 0..<index where num > nums[j] { 12 let length = dps[j] + 1 13 dps[index] = max(length, dps[index]) 14 result = max(result, dps[index]) 15 } 16 } 17 18 return result 19 } 20 } 388ms 1 class Solution { 2 func lengthOfLIS(_ nums: [Int]) -> Int { 3 4 if nums.count == 0 { 5 return 0 6 } 7 8 var result = 1 9 var dArr = [Int](repeating: 1, count: nums.count) 10 11 for i in 0..<nums.count { 12 13 for j in 0..<i { 14 15 if(nums[j] < nums[i] && (dArr[j] + 1 >= dArr[i])) { 16 dArr[i] = dArr[j] + 1 17 } 18 } 19 result = dArr[i] > result ? dArr[i] : result 20 } 21 return result 22 } 23 }
|
请发表评论