6.18 removeDupFromSortedArray I,

2016-08-22  本文已影响4人  陈十十
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() == 0) return 0;
        int wi = 0;
        for (int ri=1; ri<nums.size(); ++ri) {
            if (nums[ri]!=nums[wi]) {
                nums[++wi] = nums[ri];
            }
        }
        return ++wi;
    }

0] Remove Duplicates from Sorted Array II

        if (nums.size() < 3) return nums.size();
        int wi=1;
        for (int j=2; j<nums.size(); ++j) {
            if (nums[j] != nums[wi-1]) {
                nums[++wi] = nums[j];
            }
        }
        return ++wi;

1] Remove Duplicates from Sorted List

    ListNode* deleteDuplicates(ListNode* head) {
        if (!head || !head->next) return head;
        for (ListNode* curr=head; curr; curr=curr->next) {
            ListNode* next = curr->next;
            while (next && curr->val == next->val) {
                next = next->next;
            }
            curr->next = next;
        }
        return head;
    }

2] Remove Duplicates from Sorted List II

redo

    ListNode* deleteDuplicates(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode dummy(-1);
        dummy.next = head;

        for(ListNode* prev=&dummy, *curr=head; curr; curr=prev->next) {
            if (!curr->next || curr->val != curr->next->val) {
                prev = curr;
            } else {
                int skip = curr->val;
                do {curr = curr->next; } while (curr && curr->val == skip);
                prev->next = curr;
            }
        }

        return dummy.next;
    }

3] Rotate List

    ListNode* rotateRight(ListNode* head, int k) {
        if (!head || k<0) return head;
        ListNode* tail = head;
        int cts = 1;
        while (tail->next) {
            tail = tail->next;
            ++cts;
        }
        tail->next = head;

        int steps = cts - k%cts;
        while (steps-->0) tail = tail->next;
        head = tail->next;
        tail->next = NULL;
        return head;
    }
上一篇下一篇

猜你喜欢

热点阅读