[LeetCode]Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array


把有一排序過的整數陣列,移除重複元素後,計算該陣列有多少唯一值。這題運用的概念是 In-place algorithm 原地演算法或是就地演算法,利用本身的資料結構進行變換的演算法。

Example 1

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).


解法

用 PHP 內建函數 array_unique() 移除陣列中的重複的值。

class Solution
{

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function removeDuplicates(&$nums)
    {
        $nums = array_unique($nums);
        return count($nums);
    }
}

用原地演算法,判斷是否與上個元素是否相同,如果相同則移除該元素。

class Solution
{

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function removeDuplicates(&$nums)
    {
        $count = count($nums);
        for ($i = 0; $i < $count; $i++) {
            if ($nums[$i] == $nums[$i - 1]) {
                unset($nums[$i - 1]);
            }
        }
        return count($nums);
    }
}






留言