2019年9月27日 星期五

線性資料結構 --- array (3)

只有不斷學習,練習,,複習才會越來越厲害

因此開始記錄依照不同資料結構搭配Leetcode來練習

方便未來可以隨時拿來複習




Leetcode出處 : https://leetcode.com/problems/longest-consecutive-sequence/


                                 Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.



分析

因為題目說是unsorted integer,但是又說complexity必須是O(n)
因此,需要想到用hash table
我打算用unsorted_set來解此問題,並且以set裡面的元素為中心向外尋找下一個職是否在set裡,直到不連續為止
乍看之下時間複雜度是O(n^2),但是因為在numsSet.erase(j)後,之前出現過的就不會再進入內層兩個迴圈裡,因此類積下來的次數就是nums元素個數。
另外,如果沒有說到要O(n),我們可以先排序再做,因此時間複雜度就是O(n log n)



Sample Code (C++)

2019年9月26日 星期四

線性資料結構 --- array (2)

只有不斷學習,練習,,複習才會越來越厲害

因此,開始記錄依照不同資料結構搭配Leetcode來練習

方便未來可以隨時拿來複


Leetcode出處 : /https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/


                                 Remove Duplicates from Sorted Array II
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.


Example 1:

Given nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.



分析

和Remove Duplicates from Sorted Array解法差不多



Sample Code (C++)

線性資料結構 --- array (1)


只有不斷學習,練習,,複習才會越來越厲害
因此,開始記錄依照不同資料結構搭配Leetcode來練習
方便未來可以隨時拿來複習


Leetcode出處 : https://leetcode.com/problems/remove-duplicates-from-sorted-array/

             Remove Duplicates from Sorted Array

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 


Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.


Sample Code (C++)