Given a sorted array, remove the duplicates in place such that each element appear onlyonceand return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input arraynums=[1,1,2],

Your function should return length =2, with the first two elements ofnumsbeing1and2respectively. It doesn't matter what you leave beyond the new length.

Solution:

  1. Empty array, then return 0
  2. Double pointer problem, so get i and j.
  3. Ending condition is j = n, so while (j < n)
  4. want to find the next one such as nums[i] != nums[j]. since this is double while problem, need to have the condition of the outer while in the condition of inner while loop. Hence, the outcome will be either j out of bound or find a new value. If out of bound, then break, otherwise update the position of i and assign to it nums[j].
  5. Finally the 0,1,...,i are the new values. Hence there are i+1 distinct values.
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* p1 = head;
        if (p1 == NULL) return p1;
        ListNode* p2 = p1->next;
        while (p2 != NULL) {
            while (p2 != NULL && (p2->val == p1->val))
                p2 = p2->next;
            p1->next = p2;
            p1 = p2;
            if (p2 != NULL)
                p2 = p2->next;
        }
        return head;
    }
};

results matching ""

    No results matching ""