Created
June 15, 2017 20:02
-
-
Save jianminchen/d893d2e9683e5e7b02b77185876ae63e to your computer and use it in GitHub Desktop.
Leetcode 300 - longest subsequence using binary search - pass online judge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Leetcode300_LongestIncreasingSubsequence | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var testcase = new int[] {10, 9, 2, 5, 3, 7, 101, 18 }; | |
var length = lengthOfLIS(testcase); | |
} | |
/// <summary> | |
/// Leetcode 300 | |
/// problem statement | |
/// https://leetcode.com/problems/longest-increasing-subsequence/#/description | |
/// discussion | |
/// https://discuss.leetcode.com/topic/28719/short-java-solution-using-dp-o-n-log-n/15 | |
/// | |
/// Read Array.BinarySearch document of C# | |
/// </summary> | |
/// <param name="nums"></param> | |
/// <returns></returns> | |
public static int lengthOfLIS(int[] nums) { | |
var subSequence = new int[nums.Length]; // increasing subsequence | |
int length = 0; | |
foreach(var x in nums) { | |
int position = Array.BinarySearch(subSequence, 0, length, x); | |
// If the index is negative, it represents the bitwise | |
// complement of the next larger element in the array. | |
// | |
if (position < 0) | |
{ | |
position = -(position + 1); | |
} | |
// this may be a replacement of existing number or add to the end | |
subSequence[position] = x; | |
// add a new number in the subSequence | |
if (position == length) | |
{ | |
length++; | |
} | |
} | |
return length; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment