[LeetCode]-Python刷题第六周(排序类)

44 篇文章 0 订阅
38 篇文章 0 订阅

75. Sort Colors  排序颜色 (Medium)

Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library's sort function for this problem.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Follow up:

  • A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
  • Could you come up with a one-pass algorithm using only constant space?

解法:双指针two pointers,one pass。如果算上迭代用的index,就有三个指针。利用只有3个颜色的特点,使用left, right双指针来指向记录处理过的0和2的边界位置。一开始,两个指针分别指向头和尾,然后遍历数组。当遇到0时,和left指针的数交换,然后将left指针向右移1位。当遇到2时,和右指针的数交换,然后将右指针向左移1位。遇到1时,不做处理,进入到下一数。当遇到right指针时,就已经排完序了,所有0都被交换到了前面,所有2都被交换到了后面。

class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        def triPartiton(nums, target):
            left, idx, right = 0, 0, len(nums) - 1
            while idx <= right:
                if nums[idx] < target:
                    nums[left], nums[idx] = nums[idx], nums[left]
                    left += 1
                    idx += 1
                elif nums[idx] > target:
                    nums[idx], nums[right] = nums[right], nums[idx]
                    right -= 1
                else:
                    idx += 1
                    
        triPartiton(nums, 1)

148. Sort List 列表排序 (Medium)

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

Example 1:

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

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

解法:归并排序。由于有时间和空间复杂度的要求。把链表从中间分开,递归下去,都最后两个node时开始合并,返回上一层继续合并,直到结束。找中间点的方法可以用快慢指针,快指针走2步,慢指针走1步。也可以求出链表长度,再分开链表。1. 把链表从中间分开Break the list to two in the middle.  2. 递归排序两个子链表Recursively sort the two sub lists.  3. 合并子链表Merge the two sub lists. 

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next: return head
        pre, slow, fast = head, head, head
        while fast and fast.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next
        pre.next = None
        l1 = self.sortList(head)
        l2 = self.sortList(slow)
        return self.mergeTwoLists(l1, l2)
    
    def mergeTwoLists(self, l1, l2):
        head = ListNode(0)
        move = head
        if not l1: return l2
        if not l2: return l1
        while l1 and l2:
            if l1.val < l2.val:
                move.next = l1
                l1 = l1.next
            else:
                move.next = l2
                l2 = l2.next
            move = move.next
        move.next = l1 if l1 else l2
        return head.next

56. Merge Intervals  合并间隔 (Medium)

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

解法:给定一个有重叠的区间集合,合并所有重叠的区间。先对区间以第一个元素进行排序,定义一个变量result记录合并后的区间。然后迭代这些区间,如果区间的开始值大于result的最后一个区间的结尾值,说明整个区间都在result的最后一个区间的右侧,直接添加到result。如果区间开始值小于result的最后一个区间的结尾值,则有重合需要合并,result中的最后一个区间的尾部值变为两个尾部中的最大值。

# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution(object):
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """
        intervals = sorted(intervals, key=lambda x: x.start)
        result = []
        for interval in intervals:
            if len(result) == 0 or result[-1].end < interval.start:
                result.append(interval)
            else:
                result[-1].end = max(result[-1].end, interval.end)
        return result

57. Insert Interval  插入间隔 (Hard)

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

解法:新建一个数组,先把结尾小于新区间开始的区间写入数组,然后对于后边的和新区间进行合并,生成新的区间,直到新区间的结束小于后边区间的开始,写入这个合并后的新区间和后边剩余的区间到新数组。还有一种做法是,这里要插入一个区间,就要比较新区间和就的区间列表中的区间,如果不需要合并,就直接插入。如果需要合并,则要合并新区间,并删除不需要的区间。

# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution(object):
    def insert(self, intervals, newInterval):
        """
        :type intervals: List[Interval]
        :type newInterval: Interval
        :rtype: List[Interval]
        """
        results = []
        insertPos = 0
        for interval in intervals:
            if interval.end < newInterval.start:
                results.append(interval)
                insertPos += 1
            elif interval.start > newInterval.end:
                results.append(interval)
            else:
                newInterval.start = min(interval.start, newInterval.start)
                newInterval.end = max(interval.end, newInterval.end)
        results.insert(insertPos, newInterval)
        return results

147. Insertion Sort List  插入法排序一个列表 (Medium)

Sort a linked list using insertion sort.


A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
 

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
  3. It repeats until no input elements remain.


Example 1:

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

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

 解法:第一步:为了避免超时,要判断新结点是否有插入左边的必要,通过新结点与左边的邻结点比较,只有在值小于左边的邻结点才插入 ;第二步:从头结点开始,依次判断新结点插入位置,若新结点值比左边结点大,则p1指针右移。由于第一步比较,所以左边一定能找到比新结点大的结点;第三步:找到新结点插入的位置,将新结点插入 
注意:新结点插入时,需要将新结点赋予给临时结点,然后立即把新结点后面的结点拼接到新结点前一结点后,再将临时结点插入新位置,否则操作顺序一反会导致临时结点操作改变新结点后的结点!!! 

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next: return head
        root = TreeNode(0)
        root.next = head
        while head.next:
            if head.val <= head.next.val:    #如果当前值小于等于下一个值
                head = head.next      #就向后移一步
            else:           #如果当前值大于下一个值:
                temp = head.next
                q = root
                head.next = head.next.next
                while q.next and q.next.val < temp.val:
                    q = q.next
                temp.next = q.next
                q.next = temp
        return root.next

349. Intersection of Two Arrays  两个数组的交集 (Easy)

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

解法:由于结果中要求元素是唯一的,所以用set来统计num1 中的数字。再循环num2中的数字,在set中存在就记录到结果中,同时从set中删除。

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        
        另一种方法:
        nums1=set(nums1)
        nums2=set(nums2)
        return list(nums1&nums2) 
        
        
        """
        res = []
        s = set()
        for num in nums1:
            s.add(num)
             
        for num in nums2:
            if num in s:
                res.append(num)
                s.remove(num)
                 
        return res

350. Intersection of Two Arrays II   两个数组的交集II (Easy)

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

解法:这个题比较简单,大家都会,就不瞎说了。

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = []
        if len(nums1) < len(nums2):
            for num in nums1:
                if num in nums2:
                    res.append(num)
                    nums2.remove(num)
        else:
            for num in nums2:
                if num in nums1:
                    res.append(num)
                    nums1.remove(num)
                
        return res

274. H-Index  H指数 (Medium)

Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.

According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."

Example:

Input:
citations = [3,0,6,1,5]
Output: 3 
Explanation: 
[3,0,6,1,5]means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, her h-index is 3 .

Note: If there are several possible values for h, the maximum one is taken as the h-index.

解法:这个题目的意思就是说,给一个研究者的论文被引用次数,如果排列好之后,如果一个位置上的数字小于这个位置的序号,那么这个序号就是这个研究者的H索引值。

class Solution(object):
    def hIndex(self, citations):
        """
        :type citations: List[int]
        :rtype: int
        """
        citations.sort(reverse=True)
        h = 0
        for x in citations:
            if x >= h + 1:
                h += 1
            else:
                break
        return h

275. H-Index II   H索引 II (Medium)

Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.

According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than citations each."

Example:

Input:
citations = [0,1,3,5,6]
Output: 3 
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had 
             received 0, 1, 3, 5, 6 citations respectively. 
             Since the researcher has 3 papers with at least 3 citations each and the remaining 
             two with no more than 3 citations each, her h-index is 3.

Note:

If there are several possible values for h, the maximum one is taken as the h-index.

Follow up:

  • This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
  • Could you solve it in logarithmic time complexity?
class Solution(object):
    def hIndex(self, citations):
        """
        :type citations: List[int]
        :rtype: int
        """
        n = len(citations)
        left, right = 0, n - 1
        while left <= right:
            mid = (left + right) / 2
            if citations[mid] >= n - mid:
                right = mid - 1
            else:
                left = mid + 1
        return n - left

242. Valid Anagram  验证字符 (Easy)

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

解法:利用HashMap记录s中出现的字母和数量,然后在用t的字母和数量来验证。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
 
        count = {}
 
        for c in s:
            if c.lower() in count:
                count[c.lower()] += 1
            else:
                count[c.lower()] = 1
 
        for c in t:
            if c.lower() in count:
                count[c.lower()] -= 1
            else:
                count[c.lower()] = -1
            if count[c.lower()] < 0:
                return False
 
        return True

524. Longest Word in Dictionary through Deleting 找最长的单词 (Medium)

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

Example 1:

Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

Output: 
"apple"
Example 2:
Input:
s = "abpcplea", d = ["a","b","c"]

Output: 
"a"
Note:
  1. All the strings in the input will only contain lower-case letters.
  2. The size of the dictionary won't exceed 1,000.
  3. The length of all the strings in the input won't exceed 1,000.

解法:先将列表排序,先按照字母长度排序,然后按照字典顺序排序。然后循环每一个单词,如果在字符串中这个单词的第一个字母一样,就向下循环,直到长度超出单词的长度,如果,最后长度和单词的长度一样,就返回单词,否则返回空集。

class Solution(object):
    def findLongestWord(self, s, d):
        """
        :type s: str
        :type d: List[str]
        :rtype: str
        """
        d.sort(key = lambda x: (-len(x), x))
        for word in d:
            i = 0
            for c in s:
                if i < len(word) and word[i] == c:
                    i += 1
            if i == len(word):
                return word
        return ""

324. Wiggle Sort II  摆动排序II (Medium)

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

Example 1:

Input: 
nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].

Example 2:

Input: 
nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].

Note:
You may assume all input has valid answer.

Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?

解法:将数组排序,然后将大的数放在偶数位,小的数放在奇数位,注意pop取数组的最后一位。

class Solution(object):
    def wiggleSort(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        arr = sorted(nums)
        for i in range(1, len(nums), 2): 
            nums[i] = arr.pop() 
        for i in range(0, len(nums), 2): 
            nums[i] = arr.pop() 

905. Sort Array By Parity  按奇偶校验排序数组  (Easy)

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

Example 1:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

解法:按照列表能整除2的先排序,然后,别的后边。

class Solution(object):
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        
        return sorted(A, key=lambda x: x % 2)
        
        
        
        
        

922. Sort Array By Parity II   按奇偶校验排序数组 II  (Easy)

Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.

Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.

You may return any answer array that satisfies this condition.

Example 1:

Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Note:

  1. 2 <= A.length <= 20000
  2. A.length % 2 == 0
  3. 0 <= A[i] <= 1000

解法:将数组的奇数和偶数分开,然后在结果列表中,逐个加入。

class Solution(object):
    def sortArrayByParityII(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        odd_list = []
        even_list = []
        
        for i in A:
            if i % 2 == 1:
                odd_list.append(i)
            else:
                even_list.append(i)

        result = [None]*len(A)
        result[::2] = even_list
        result[1::2] = odd_list
        return result

944. Delete Columns to Make Sorted  删除要排序的列 (Easy)

We are given an array A of N lowercase letter strings, all of the same length.

Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.

For example, if we have an array A = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"], and the remaining columns of A are ["b","v"]["e","y"], and ["f","z"].  (Formally, the c-th column is [A[0][c], A[1][c], ..., A[A.length-1][c]].)

Suppose we chose a set of deletion indices D such that after deletions, each remaining column in A is in non-decreasing sorted order.

Return the minimum possible value of D.length.

Example 1:

Input: ["cba","daf","ghi"]
Output: 1
Explanation: 
After choosing D = {1}, each column ["c","d","g"] and ["a","f","i"] are in non-decreasing sorted order.
If we chose D = {}, then a column ["b","a","h"] would not be in non-decreasing sorted order.

Example 2:

Input: ["a","b"]
Output: 0
Explanation: D = {}

Example 3:

Input: ["zyx","wvu","tsr"]
Output: 3
Explanation: D = {0, 1, 2}

Note:

  1. 1 <= A.length <= 100
  2. 1 <= A[i].length <= 1000

解法:题目大意是说有一个数组A,其中它的每个元素都是等长度的字符串。现在求最短的要删除的切片的长度,使得做完操作之后,数组中剩下的相同列是递增的。如果一个列的元素已经是递增的,那么我们一定不能把这个列删除掉。如果删除掉某一列,那么其他的列将不受到任何影响。

class Solution(object):
    def minDeletionSize(self, A):
        """
        :type A: List[str]
        :rtype: int
        """
        res = 0
        N = len(A[0])
        for i in range(N):
            col = [a[i] for a in A]  #这个时候是每一项的第i列;
            if col != sorted(col):
                res += 1
        return res

451. Sort Characters By Frequency  根据频率排列字母 (Medium)

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:

Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

解法:1)计算字母,2)对所有字母的数量进行排序,3)从具有最高计数的字母重新构造返回字符串

import collections
class Solution(object):
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str
        """
        import collections
        if not s:
            return ""
        count_s = collections.Counter(s)
        counter = count_s.most_common()
        rs = ''
        for i in counter:
            rs += i[0] * i[1]
        return rs

540. Single Element in a Sorted Array 在排序好的数组中的单一元素 (Medium)

Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.

Example 1:

Input: [1,1,2,3,3,4,4,8,8]
Output: 2

Example 2:

Input: [3,3,7,7,10,11,11]
Output: 10

Note: Your solution should run in O(log n) time and O(1) space.

解法:1)当nums[mid] == nums[mid+1]时,右侧此时就会剩下偶数个值,因此只出现一次的数字不会出现在右侧,2)反之,nums[mid] == nums[mid-1]时,左侧就会剩下偶数个值,因此只出现一次的数字不会出现在左侧

class Solution(object):
    def singleNonDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        low = 0
        high = len(nums) - 1
        while low < high:
            mid = (low + high)//2
            if mid%2 ==0:
                mid +=1
            if nums[mid] == nums[mid - 1]:
                low = mid + 1    # 在右侧
            else:
                high = mid - 1   # 在左侧
        return nums[low]
    

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值