zoukankan      html  css  js  c++  java
  • leetcode 21-30 easy

    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.

    Example:

    Input: 1->2->4, 1->3->4
    Output: 1->1->2->3->4->4

    C++

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            ListNode dummy(INT_MIN);
            ListNode *tail=&dummy;
            while(l1 && l2)
            {
                if(l1->val<l2->val)
                {
                    tail->next=l1;
                    l1=l1->next;
                    
                }
                else 
                {
                    tail->next=l2;
                    l2=l2->next;
                }
                tail=tail->next;
            }
            
            //谁没结束就补充谁
            tail->next=l1?l1:l2;
            return dummy.next;    
        }
    };

    python 

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def mergeTwoLists1(self, l1, l2):
            dummy = cur = ListNode(0)
            while l1 and l2:
                if l1.val < l2.val:
                    cur.next = l1
                    l1 = l1.next
                else:
                    cur.next = l2
                    l2 = l2.next
                cur = cur.next
            cur.next = l1 or l2
            return dummy.next
        
    # recursively    
        def mergeTwoLists2(self, l1, l2):
            if not l1 or not l2:
                return l1 or l2
            if l1.val < l2.val:
                l1.next = self.mergeTwoLists(l1.next, l2)
                return l1
            else:
                l2.next = self.mergeTwoLists(l1, l2.next)
                return l2
            
    # in-place, iteratively        
        def mergeTwoLists(self, l1, l2):
            if None in (l1, l2):
                return l1 or l2
            dummy = cur = ListNode(0)
            dummy.next = l1
            while l1 and l2:
                if l1.val < l2.val:
                    l1 = l1.next
                else:
                    nxt = cur.next
                    cur.next = l2
                    tmp = l2.next
                    l2.next = nxt
                    l2 = tmp
                cur = cur.next
            cur.next = l1 or l2
            return dummy.next

    26. Remove Duplicates from Sorted Array

    Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

    Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

    Example 1:

    Given nums = [1,1,2],
    
    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
    
    It doesn't matter what you leave beyond the returned length.

    Example 2:

    Given nums = [0,0,1,1,1,2,2,3,3,4],
    
    Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
    
    It doesn't matter what values are set beyond the returned length.
    

    Clarification:

    Confused why the returned value is an integer but your answer is an array?

    Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

    Internally you can think of this:

    // nums is passed in by reference. (i.e., without making a copy)
    int len = removeDuplicates(nums);
    
    // any modification to nums in your function would be known by the caller.
    // using the length returned by your function, it prints the first len elements.
    for (int i = 0; i < len; i++) {
        print(nums[i]);
    }

    C++

    int removeDuplicates(vector<int>& nums) {
        int i = 0;
        for (int n : nums)
            if (!i || n > nums[i-1])
                nums[i++] = n;
        return i;
    }

    python

    from collections import OrderedDict
    class Solution(object):
        def removeDuplicates(self, nums):
    
            nums[:] =  OrderedDict.fromkeys(nums).keys()
            return len(nums)
    
    
    
    ###########
    class Solution:
        # @param a list of integers
        # @return an integer
        def removeDuplicates(self, A):
            if not A:
                return 0
            end = len(A)
            read = 1
            write = 1
            while read < end:
                if A[read] != A[read-1]:
                    A[write] = A[read]
                    write += 1
                read += 1
            return write

    28、Implement strStr()

    Implement strStr().

    Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    Example 1:

    Input: haystack = "hello", needle = "ll"
    Output: 2
    

    Example 2:

    Input: haystack = "aaaaa", needle = "bba"
    Output: -1
    

    Clarification:

    What should we return when needle is an empty string? This is a great question to ask during an interview.

    For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

    C++

    //暴力算法
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            int m = haystack.length(), n = needle.length();
            if (!n) return 0;
           
            for (int i = 0; i < m - n + 1; i++) {
                int j = 0;
                for (; j < n; j++) {
                    if (haystack[i + j] != needle[j]) {
                        break;
                    }
                }
                if (j == n)  return i;
            }
            return -1;
        }
    };

    //KMP
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            int m = haystack.length(), n = needle.length();
            if (!n) {
                return 0;
            }
            vector<int> lps = kmpProcess(needle);
            for (int i = 0, j = 0; i < m; ) {
                if (haystack[i] == needle[j]) { 
                    i++;
                    j++;
                }
                if (j == n) {
                    return i - j;
                }
                if ((i < m) && (haystack[i] != needle[j])) {
                    if (j) {
                        j = lps[j - 1];
                    }
                    else {
                        i++;
                    }
                }
            }
            return -1;
        }
    private:
        vector<int> kmpProcess(string& needle) {
            int n = needle.length();
            vector<int> lps(n, 0);
            for (int i = 1, len = 0; i < n; ) {
                if (needle[i] == needle[len]) {
                    lps[i++] = ++len;
                } else if (len) {
                    len = lps[len - 1];
                } else {
                    lps[i++] = 0;
                }
            }
            return lps;
        }
    };
     
  • 相关阅读:
    单链表的算法
    顺序表的算法
    程序员的内功——数据结构和算法系列
    查找一 线性表的查找

    排序算法系列
    排序三 直接插入排序
    排序八 基数排序
    Linux编程 9 (shell类型,shell父子关系,子shell用法)
    mysql 开发进阶篇系列 41 mysql日志之慢查询日志
  • 原文地址:https://www.cnblogs.com/hotsnow/p/9548616.html
Copyright © 2011-2022 走看看