Leetcode

Populating Next Right Pointers in Each Node

 

Reversing linked list iteratively and recursively

1) The iterative way:

 

void reverse(Node*& head) {

    if (!head) return;

    Node* prev = NULL;

    Node* curr = head;

    while (curr) {

        Node* next = curr->next;

        curr->next = prev;

        prev = curr;

        curr = next;

    }

    head = prev;

}

 

 2) The recursive way:

 

void reverse(Node*& p) {

    if (!p) return;

    Node* rest = p->next;

    if (!rest) return;

    reverse(rest);

    p->next->next = p;

    p->next = NULL;

    p = rest;

}

 

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

 

set<vector<int> > find_triplets(vector<int> arr) {
    sort(arr.begin(), arr.end());
    set<vector<int> > triplets;
    vector<int> triplet(3);
    int n = arr.size();
    for (int i = 0;i < n; i++) {
        int j = i + 1;
        int k = n - 1;
        while (j < k) {
            int sum_two = arr[i] + arr[j];
            if (sum_two + arr[k] < 0) {
                j++;
            } else if (sum_two + arr[k] > 0) {
                k--;
            } else {
                triplet[0] = arr[i];
                triplet[1] = arr[j];
                triplet[2] = arr[k]; triplets.insert(triplet);
                j++;
                k--;
            }
        }
    }
    return triplets;
}
View Code

 

 

 

posted @ 2013-07-30 15:49  caniggia  阅读(104)  评论(0)    收藏  举报