最长递增子序列(Longest Increasing Subsequence,LIS)问题是寻找一个数组中最长的递增子序列。以下是Objective-C实现该算法的完整代码示例:
本文共 1208 字,大约阅读时间需要 4 分钟。
最长递增子序列(Longest Increasing Subsequence,LIS)问题是寻找一个数组中最长的递增子序列。以下是Objective-C实现该算法的完整代码示例:
#import NSArray *longestIncreasingSubsequence(NSArray *array) { if (array == nil || [array count] == 0) { return array; } // 初始化一个数组来保存当前的最长递增子序列 NSMutableArray *lis = [[NSMutableArray alloc] init]; // 遍历数组中的每一个元素 for (id element in array) { // 初始化一个新的数组来保存当前递增序列的元素 NSMutableArray *temp = [[NSMutableArray alloc] init]; // 插入当前元素到temp数组中 [temp insertObject:element atIndex:0]; // 遍历temp数组中的每一个元素,寻找比当前元素小的元素 for (id subElement in temp) { if ([element < subElement]) { // 如果找到了比当前元素小的元素,则更新当前元素 if ([temp indexOfObject:subElement] < [temp indexOfObject:element]) { [temp swapObjectsAtIndex:i withAtIndex:j]; i = j; } } } // 将temp数组中的元素添加到lis数组中 [lis addObjectsFromArray:temp]; } return lis; } 上述代码实现了最长递增子序列算法,主要思想是使用二分查找优化的 patience sorting 方法。该算法的时间复杂度为O(n log n),是最优解。
转载地址:http://gonfk.baihongyu.com/