LeetCode41/19 First Missing Positive/Remove Nth Node From End of List ****

一:leetcode41 First Missing Positive

题目:

Given an unsorted integer array, find the first missing positive integer.

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

Your algorithm should run in O(n) time and uses constant space.

分析:此题关键O(n)和常量空间的限制。常量空间的话第一可以考虑是不是固定数量的几个变量能搞定;否则可以考虑是不是问题本身已经提供了足够的空间。当然这里O(1)就可以解决。

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        for(int i = 0; i < n; i++){
            while(A[i] > 0 && A[i] <= n &&  A[A[i]-1] != A[i]){  //  比如1 2 5 6 7    此时的A[2]的5就需要与A[4]交换
                swap(A[i], A[A[i]-1]);//// 注意条件是让别人正确,不是自己位置A[i]!=i+1 否则如[1 1]就会陷入死循环
            }
        }
        for(int i = 0; i < n; i++)
            if(A[i] != i+1) return i+1;
        return n+1;
        
    }
};

很多人认为这不是O(N)时间,其实虽然当条件满足,i没有++,但是此时可以是A[A[i]-1]的值变成了A[i],当循环到下标A[i]-1,条件肯定不满足,故还是O(N)时间。当然了本问题没有必要限制数据不重复。。。It is amazing!!

二:LeetCode19 Remove Nth Node From End of List

题目:

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.
分析:这题给出两种方法,方法一需要额外的空间复杂度O(N),,方法二是双指针的思想,关键在于很难想到啊

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/*class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {    // 需要空间复杂度O(N)
        ListNode *p = head;
        while(p != NULL){
            vec.push_back(p);
            p = p->next;
        }
        int len = vec.size();
        if(n == len) head = head->next;
        else vec[len-n-1]->next = vec[len-n]->next;
        return head;
    }
private:
    vector<ListNode*> vec;
};*/

class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *front= head, *behind=head;
        while(front != NULL){
            front = front->next;
            if(n-- < 0) behind = behind->next;
        }
        if(n >= 0)head = head->next;
        else behind->next = behind->next->next;
        return head;
    }

};



你可能感兴趣的:(array)