1. public class Solution {
    2. /**
    3. * retrun the longest increasing subsequence
    4. * @param arr int整型一维数组 the array
    5. * @return int整型一维数组
    6. */
    7. public int[] LIS (int[] arr) {
    8. // write code here
    9. //tails[k]表示长度为k+1的最长递增子序列的末尾元素
    10. int[] tails = new int[arr.length];
    11. tails[0] = arr[0];
    12. int end = 0;
    13. //记录以当前元素为结尾的最长递增子序列的长度
    14. int[] maxLen = new int[arr.length];
    15. Arrays.fill(maxLen, 1);
    16. for (int i = 1; i < arr.length; i++) {
    17. int left = 0;
    18. int right = end + 1;
    19. while (left < right) {
    20. int mid = left + (right - left) / 2;
    21. if (arr[i] > tails[mid]) {
    22. left = mid + 1;
    23. } else {
    24. right = mid;
    25. }
    26. }
    27. tails[left] = arr[i];
    28. if (left == end + 1) end++;
    29. if (left + 1 > maxLen[i]) maxLen[i] = left + 1;
    30. }
    31. int[] res = new int[end + 1];
    32. for (int i = arr.length - 1, j = res.length; j > 0; i--) {
    33. if (maxLen[i] == j) {
    34. res[--j] = arr[i];
    35. }
    36. }
    37. return res;
    38. }
    39. }