leetcode 笔记

leetcode 笔记

Linked List


2. Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

      Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
      Output: 7 -> 0 -> 8

#include <string>
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 错误原因:res = res -> next;漏掉
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* res = new ListNode(0);
        ListNode* new_head = res;
        int sum = 0;
        while (l1 || l2) {
            if (l1) {
                sum += l1 -> val;
                l1 = l1 -> next;
            }
            if (l2) {
                sum += l2 -> val;
                l2 = l2 -> next;
            }
            res = res -> next = new ListNode(sum%10);    // @1
            sum /= 10;
        }
        if (sum) res -> next = new ListNode(sum);
        return new_head -> next;
    }
}

// 思路:避免类似444+556的情况,while中不要用&&


19. 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.

Note:
Given n will always be valid.

#include <string>
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// 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) {
        ListNode** t1 = &head, *t2 = head;
        for(int i = 1; i < n; ++i)
        {
            t2 = t2->next;
        }
        while(t2->next != NULL)
        {
            t1 = &((*t1)->next);
            t2 = t2->next;
        }
        *t1 = (*t1)->next;
        return head;
    }
};
// 思路:待删节点定义为二级指针,将地址改变(tasty code o.o)

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* front_remove = head;
        int cnt_n = 0;
        ListNode* cur_node = head;
        while (cur_node != NULL) {
            if (cnt_n > n) front_remove = front_remove -> next;
            else cnt_n++;
            cur_node = cur_node -> next;
        }
        if (cnt_n > n) front_remove -> next = front_remove -> next -> next;
        else if (cnt_n == n) head = head -> next;
        return head;
    }
};
// 思路:一般解法;或者新建头节点。

21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

#include <string>
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* res = new ListNode(0);
        ListNode* ptr = res;
        while (l1 != NULL && l2 != NULL) {
            if (l1 -> val < l2 -> val) {
                ptr -> next = l1;
                l1 = l1 -> next;
            } else {
                ptr -> next = l2;
                l2 = l2 -> next;
            }
            ptr = ptr -> next;
        }
        if (l1 == NULL) ptr -> next = l2;
        if (l2 == NULL) ptr -> next = l1;
        return res -> next;
    }


    ListNode *mergeTwoLists_recursive(ListNode *l1, ListNode *l2) {
        if(l1 == NULL) return l2;
        if(l2 == NULL) return l1;

        if(l1->val < l2->val) {
            l1->next = mergeTwoLists_recursive(l1->next, l2);
            return l1;
        } else {
            l2->next = mergeTwoLists_recursive(l2->next, l1);
            return l2;
        }
    }
};
// 思路:递归和非递归

23. Merge k Sorted Lists

不熟练
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

struct compare {
    bool operator()(const ListNode* l, const ListNode* r) {
        return l->val > r->val;
    }
};

class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*, vector<ListNode*>, compare> q;
        for (int i = 0; i < lists.size(); i++) {  // for (auto i : lists)
            if (lists[i]) q.push(lists[i]);
        }
        if(q.empty())  return NULL;
        ListNode* result = q.top();
        ListNode* ptr = q.top();
        q.pop();
        if (result -> next) q.push(result -> next);
        while (!q.empty()) {
            ptr -> next = q.top();
            q.pop();
            ptr = ptr -> next;
            if (ptr -> next) q.push(ptr -> next);
        }
        return result;
    }
};
// 思路:优先队列

24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL || head -> next == NULL) return head;
        ListNode* result = new ListNode(0);
        ListNode* last = result;
        ListNode* temp = head;
        while (temp != NULL && temp -> next != NULL) {
            // cout << temp -> val << endl;
            last -> next = temp -> next;
            last = temp;
            temp = temp -> next -> next;
            last -> next -> next = last;
        }
        last -> next = temp;
        return result -> next;
    }

/*********没看懂****************/
    ListNode* swapPairs2(ListNode* head) {
        ListNode **pp = &head, *a, *b;
        while ((a = *pp) && (b = a->next)) {
            a->next = b->next;
            b->next = a;
            *pp = b;
            pp = &(a->next);
        }
        return head;
    }
/************************/
};

25. Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

    Given this linked list: 1->2->3->4->5
    For k = 2, you should return: 2->1->4->3->5
    For k = 3, you should return: 3->2->1->4->5
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* reverseKGroup_recursive(ListNode* head, int k) {
        //**************待解决************//


    }

    ListNode* reverseKGroup(ListNode* head, int k) {
        if (head == NULL || k < 2) return head;
        ListNode* last = new ListNode(0);
        ListNode* result = last;
        ListNode* first;
        ListNode* second = head;
        ListNode* third = head -> next;
        ListNode* tmp = head;
        ListNode* cur = head;
        int cnt = 0;
        while (1) {
            while (cnt < k && cur != NULL && third != NULL) {
                cur = cur -> next;
                ++cnt;
            }
            if (cnt < k) {
                last -> next = second;
                return result -> next;
            }
            while (--cnt) {
                first = second;
                // cout << first -> val << " ";
                second = third;
                third = second -> next;
                second -> next = first;
            }
            last -> next = second;
            last = tmp;
            tmp = cur;
            first = second;
            second = third;
            if (third != NULL) third = second -> next;
        }
        return result -> next;
    }
};

61. Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:

 Given 1->2->3->4->5->NULL and k = 2,
 return 4->5->1->2->3->NULL.
// 忽略了k大于size的情况
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == NULL) return head;
        ListNode* tail = head;
        int cnt = 1;
        while (tail -> next != NULL) {
            tail = tail -> next;
            ++cnt;
        }
        tail -> next = head;
        if (k%cnt > 0) {
            for (int i = cnt - k%cnt; i > 0; --i) tail = tail -> next;
        }
        head = tail -> next;
        tail -> next = NULL;
        return head;
    }
};
// 思路:连接头尾,再拆开

82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == NULL) return head;
        ListNode* last = new ListNode(0);
        last -> next = head;
        ListNode* ptr = head;
        ListNode* newhead = last;
        while (ptr != NULL) {
            if (ptr -> next == NULL || ptr -> val != ptr -> next -> val) {
                if (last -> next != ptr) last -> next = ptr -> next;
                else last = last -> next;
            }
            if (ptr != NULL) ptr = ptr -> next;
        }
        return newhead -> next;
    }
};

83. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

   Given 1->1->2, return 1->2.
   Given 1->1->2->3->3, return 1->2->3.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* last = new ListNode(0);
        last -> next = head;
        ListNode* ptr = head;
        head = last;
        while (ptr != NULL) {
            if (ptr -> next == NULL || ptr -> val != ptr -> next -> val) {
                if (last -> next != ptr) last -> next = ptr;
                last = ptr;
            }
            ptr = ptr -> next;
        }
        return head -> next;
    }
};

86. Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,

   Given 1->4->3->2->5->2 and x = 3,
   return 1->2->2->4->3->5.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode left(0), right(0);
        ListNode *p_left = &left, *p_right = &right;
        while (head) {
            if (head -> val < x) p_left = p_left -> next = head;
            else p_right = p_right -> next = head;
            head = head -> next;
        }
        p_right -> next = NULL;
        p_left -> next = right.next;
        return left.next;
    }
};

92. Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:

   Given 1->2->3->4->5->NULL, m = 2 and n = 4,
   return 1->4->3->2->5->NULL.
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* new_head = new ListNode(0);
        new_head -> next = head;
        ListNode* first = new_head;
        int k = m;
        while (--k) first = first -> next;
        ListNode* second = first -> next;
        ListNode* third = second -> next;
        while (n-- > m) {
            second -> next = third -> next;
            third -> next = first -> next;
            first -> next = third;
            third = second -> next;
        }
        return new_head -> next;
    }
};

// 我的实现
class Solution2 {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* new_head = new ListNode(0);
        new_head -> next = head;
        ListNode* left = new_head;
        int k = m;
        while (--k) left = left -> next;
        ListNode* first = left -> next;
        ListNode* right = first;
        ListNode* second = first -> next;
        ListNode* third;
        while (n-- > m) {
            third = second -> next;
            second -> next = first;
            first = second;
            second = third;
        }
        left -> next = first;
        right -> next = second;
        return new_head -> next;
    }
};

109. Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};


struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if (head == NULL) return head;
        return func(head, NULL);
    }
    TreeNode* func(ListNode* head, ListNode* tail) {
        if (head == tail) return NULL;
        ListNode* middle = head;
        ListNode* ptail = head;
        while (ptail != tail && ptail -> next != tail) {
            middle = middle -> next;
            ptail = ptail -> next -> next;
        }
        TreeNode* add = new TreeNode(middle -> val);
        add -> left = func(head, middle);
        add -> right = func(middle -> next, tail);
        return add;
    }
};

// java reference-1
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
    if(head==null) return null;
    return toBST(head,null);
}
public TreeNode toBST(ListNode head, ListNode tail){
    ListNode slow = head;
    ListNode fast = head;
    if(head==tail) return null;

    while(fast!=tail&&fast.next!=tail){
        fast = fast.next.next;
        slow = slow.next;
    }
    TreeNode thead = new TreeNode(slow.val);
    thead.left = toBST(head,slow);
    thead.right = toBST(slow.next,tail);
    return thead;
}


// java reference-2
private ListNode node;

public TreeNode sortedListToBST(ListNode head) {
    if(head == null){
        return null;
    }

    int size = 0;
    ListNode runner = head;
    node = head;

    while(runner != null){
        runner = runner.next;
        size ++;
    }

    return inorderHelper(0, size - 1);
}

public TreeNode inorderHelper(int start, int end){
    if(start > end){
        return null;
    }

    int mid = start + (end - start) / 2;
    TreeNode left = inorderHelper(start, mid - 1);

    TreeNode treenode = new TreeNode(node.val);
    treenode.left = left;
    node = node.next;

    TreeNode right = inorderHelper(mid + 1, end);
    treenode.right = right;

    return treenode;
}

138. Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

struct RandomListNode {
    int label;
    RandomListNode *next, *random;
    RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};

// 错误原因:1漏掉;2指向空指针的情况;3不能两个while,必须先处理掉random
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if (head == NULL) return NULL;   //@1
        RandomListNode* ptr = head;
        while (ptr != NULL) {
            RandomListNode* new_node = new RandomListNode(ptr -> label);
            new_node -> next = ptr ->next;
            new_node -> random = ptr -> random;
            ptr -> next = new_node;
            ptr = new_node -> next;
        }
        ptr = head;
        while (ptr) {
            ptr = ptr -> next;
            if (ptr -> random) ptr -> random = ptr -> random -> next;  // @2
            ptr = ptr -> next;
        }
        RandomListNode* origin = head;
        RandomListNode* new_head = new RandomListNode(0);
        ptr = new_head;
        while (origin) {
            ptr -> next = origin -> next;
            ptr = ptr -> next;
            origin -> next = ptr -> next;
            origin = origin -> next;
        }
        return new_head -> next;
    }
};

141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 错误原因,while条件不全
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (head == NULL) return 0;
        ListNode* fast = head, *slow = head;
        while (fast && fast -> next && fast -> next -> next) {
            fast = fast -> next -> next;
            slow = slow -> next;
            if (fast == slow) return 1;
        }
        return 0;
    }
};

142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 没搞太懂
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if (head == NULL || head -> next == NULL) return NULL;
        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* meet_point = head;
        while (fast -> next != NULL && fast -> next -> next != NULL) {
            slow = slow -> next;
            fast = fast -> next -> next;
            if (slow == fast) {
                while (slow != meet_point) {
                    slow = slow -> next;
                    meet_point = meet_point -> next;
                }
                return meet_point;
            }
        }
        return NULL;
    }
};

143. Reorder List

Given a singly linked list L: L0→L1→…→Ln-1→Ln,

reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes’ values.

For example,

    Given {1,2,3,4}, reorder it to {1,4,2,3}.
class Solution {
public:
    void reorderList(ListNode* head) {
        if (head == NULL || head -> next == NULL || head -> next -> next == NULL) return;  //@1
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast -> next && fast -> next -> next) {
            slow = slow -> next;
            fast = fast -> next -> next;
        }

        ListNode* first = slow -> next;
        slow -> next = NULL;                   //@2
        ListNode* second = first -> next;
        ListNode* third;
        first -> next = NULL;
        while (second) {
            third = second -> next;
            second -> next = first;
            first = second;
            second = third;
        }

        second = first;
        first = head;
        third = first -> next;
        while (second) {
            first -> next = second;
            first = second;
            second = third;
            third = first -> next;
        }
        return;
    }
};

147. Insertion Sort List

Sort a linked list using insertion sort.

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 错误原因:@1写成了:second = head;
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if (head == NULL || head -> next == NULL) return head;
        ListNode* new_head = new ListNode(0);
        new_head -> next = head;
        ListNode* first = new_head;
        ListNode* second = head;
        ListNode* third = second -> next;
        second -> next = NULL;
        while (third != NULL) {
            while (second != NULL && second -> val < third -> val) {
                first = second;
                second = second -> next;
            }
            first -> next = third;
            third = third -> next;
            first -> next -> next = second;
            first = new_head;
            second = first -> next;    // @1
        }
        return new_head -> next;
    }
};

148. Sort List

Sort a linked list in O(n log n) time using constant space complexity.

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 错误原因:@1写成了||
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (head == NULL || head -> next == NULL) return head;
        ListNode* slow = head, *fast = head;
        ListNode* right, *left;
        while (fast -> next != NULL && fast -> next -> next != NULL) {
            slow = slow -> next;
            fast = fast -> next -> next;
        }
        fast = slow -> next;
        slow -> next = NULL;
        left =  sortList(head);
        right = sortList(fast);
        ListNode* merge_list = new ListNode(0);
        ListNode* new_head = merge_list;
        while (left && right) {    //@!
            if (left -> val < right -> val) {
                merge_list -> next = left;
                merge_list = left;
                left = left -> next;
            }
            else {
                merge_list -> next = right;
                merge_list = right;
                right = right -> next;
            }
        }
        merge_list -> next = left ? left : right;
        return new_head -> next;
    }
};

160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// ac
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (headA == NULL || headB == NULL) return NULL;
        ListNode* nodeA = headA;
        ListNode* nodeB = headB;
        while (nodeA != nodeB) {
            nodeA = nodeA == NULL ? headB : nodeA -> next;
            nodeB = nodeB == NULL ? headA : nodeB -> next;
        }
        return nodeA;
    }
};

// 思路:遍历两次,第一次用来计算长度的差值

203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example

  Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
  Return: 1 --> 2 --> 3 --> 4 --> 5
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// ac
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode* new_head = new ListNode(0);
        new_head -> next = head;
        ListNode* pre = head;
        ListNode* last = new_head;
        while (pre) {
            if (pre -> val == val) {
                last -> next = pre -> next;
                pre = last -> next;
            }
            else {
                last = pre;
                pre = pre -> next;
            }
        }
        return new_head -> next;
    }
};

// 递归
public ListNode removeElements(ListNode head, int val) {
        if (head == null) return null;
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
}

206. Reverse Linked List

Reverse a singly linked list.

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 错误原因:@1:少了尾部赋值
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL || head -> next == NULL) return head;
        ListNode* new_head = reverseList(head -> next);
        head -> next -> next = head;
        head -> next = NULL;   //@1
        return new_head;
    }
};

234. Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

do it in O(n) time and O(1) space

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 错误:低级错误。。。
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode* new_head = new ListNode(0);
        new_head -> next = head;
        ListNode* fast = new_head;
        ListNode* slow = new_head;
        while (fast -> next && fast -> next -> next) {
            slow = slow -> next;
            fast = fast -> next -> next;   //@1
        }
        fast = reverseList(slow -> next);
        slow -> next = NULL;
        slow = head;
        while (slow) {
            if (fast -> val != slow -> val) return false;
            fast = fast -> next;
            slow = slow -> next;
        }
        return true;
    }
    ListNode* reverseList(ListNode* head) {
        if (head == NULL || head -> next == NULL) return head;
        ListNode* first = NULL;
        ListNode* second = head;
        ListNode* third;     //@2
        while (second) {
            third = second -> next;
            second -> next = first;
            first = second;
            second = third;
        }
        return first;
    }
};

237. Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution1 {
public:
    void deleteNode(ListNode* node) {
        auto next = node -> next;
        *node = *(node -> next);
        delete next;
    }
};

328. Odd Even Linked List

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example:

  Given 1->2->3->4->5->NULL,
  return 1->3->5->2->4->NULL.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// ac
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if (head == NULL || head -> next == NULL || head -> next -> next == NULL) return head;
        ListNode* odd = head;
        ListNode* even = head -> next;
        ListNode* even_head = even;
        while (odd -> next && odd -> next -> next) {
            odd = odd -> next = odd -> next -> next;
            even = even -> next = even -> next -> next;
        }
        odd -> next = even_head;
        return head;
    }
};
// 思路:分别计算奇偶链表,再合并

445. Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Example:

  Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
  Output: 7 -> 8 -> 0 -> 7
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// ac
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        stack<int> l1_stack;
        stack<int> l2_stack;
        int sum = 0;
        ListNode* res = NULL;
        for (; l1 != NULL; l1 = l1 -> next) l1_stack.push(l1 -> val);
        for (; l2 != NULL; l2 = l2 -> next) l2_stack.push(l2 -> val);
        while (!l1_stack.empty() || !l2_stack.empty()) {
            if (!l1_stack.empty()) {
                sum += l1_stack.top();
                l1_stack.pop();
            }
            if (!l2_stack.empty()) {
                sum += l2_stack.top();
                l2_stack.pop();
            }
            ListNode* node = new ListNode(sum%10);
            node -> next = res;
            res = node;
            sum = sum/10;
        }
        if (sum) {
            ListNode* node = new ListNode(sum);
            node -> next = res;
            res = node;
        }
        return res;
    }
};
// 思路:使用栈

Array


1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

   Given nums = [2, 7, 11, 15], target = 9,
   Because nums[0] + nums[1] = 2 + 7 = 9,
   return [0, 1].
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hash;
        vector<int> result;
        for (int i = 0; i < nums.size(); i++) {
            if (hash.find(target - nums[i]) != hash.end()) {
                result.push_back(hash[target - nums[i]]);
                result.push_back(i);
                return result;
            }
            hash[nums[i]] = i;
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值