• Leetcode之数组(前200道)


    持续更新...

    github链接:https://github.com/x2mercy/Leetcode_Solution

    EASY:

    1. Two Sum:

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

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            hash_map={}
            for i,val in enumerate(nums):
                hash_map[val]=i
            for j,val in enumerate(nums):
                if target-val in nums:
                    k=hash_map[target-val]
                    if j!=k:
                        return j,k
                    
                
            

    这道题应该是我刷Leetcode的第一题!哈哈哈哈还不习惯用字典,连字典的名字都是hash_map

    需特别注意:nums里的数每个只能用一遍!

    这道题的trick在于把array里的元素存入字典以后,只要在原array里寻找有没有target-val就行了,然后存入字典,返回index

    2. Remove Duplicates from Sorted Array:

    Given a sorted array, 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.

    class Solution(object):
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums:
                return 0
            j=0
            for i in range (len(nums)):
                if nums[i]!=nums[j]:
                    j+=1
                    nums[j]=nums[i]
            return j+1
            
    本来想从第一个元素开始,挨个比较,然后用del操作删掉重复的元素,但是定义nums[i+1]会报错:list index out of range,
    题目又说不可以allocate另外一个列表来做,所以定义j来作为中间值,如果num[i]!=num[j],则j+1,将num[i]的值赋给num[j],
    如果相等,则继续i+1比较下一个元素,这样最后将j+1就是len。

    3. Remove Element:

    Given an array and a value, remove all instances of that value in-place 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.

    The order of elements can be changed. It doesn't matter what you leave beyond the new length.

    class Solution(object):
        def removeElement(self, nums, val):
            """
            :type nums: List[int]
            :type val: int
            :rtype: int
            """
            j=0
            if not nums:
                return 0
            for i in range(len(nums)):
                if nums[i]!=val:
                    nums[j]=nums[i]
                    j=j+1
            return j
    这道题刚开始按照上一题的做法做,发现会报错,因为j一开始为0,所以j[0]会被读出,所以调换了j+1和num[j]=num[i]的顺序
    4. Search Insert Position:
    Given a sorted array and a target value, return the index if the target is found.
    If not, return the index where it would be if it were inserted in order.
    class Solution(object):
        def searchInsert(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            if target in nums:
                for i in range(len(nums)):
                    if nums[i]==target:
                        return i
            else:
                nums.append(target)
                nums.sort()
                for j in range(len(nums)):
                    if nums[j]==target:
                        return j

    这道题很简单了,当时写完之后没有做什么笔记,大概就是如果target在nums里,就一个一个比较返回index,如果不在就先append,在sort一下,返回index

     5. Maximum Subarray:

    Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

    For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
    the contiguous subarray [4,-1,2,1] has the largest sum = 6.

    这道题我写了两种解法,一种虽然跑过了case但是如果数组很长就会time limit exceed,另一种是ok的

    第一种(time limit exceed):

    # This solution is not perfect because  Time Limit Exceeded will happen when input a list with a lot of numbers
    class Solution(object):
        def maxSubArray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums:
                return 0
            else:
                max_s=[]
                for i in range(len(nums)):
                    current_sums=nums[i]
                    for j in range(i+1,len(nums)):
                        current_sums+=nums[j]
                        max_s.append(current_sums)
                for i in range(len(nums)):
                    max_s.append(nums[i])
                max_s.sort()
                return max_s[len(max_s)-1]
    第二种(perfect):
    class Solution(object):
        def maxSubArray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums:
                return 0
            else:
                current=nums[0]
                max_sums=nums[0]
                for i in range(1,len(nums)):
                    current=max(nums[i],current+nums[i])
                    max_sums=max(current,max_sums)
                return max_sums   
    
    
    
    第一种会超时是因为我开辟了另一个list来存放所有的相邻元素的和,然后再sort这个List,返回最后的那个元素
    第二种比较机智,因为不用开辟新的list来存放元素和,只需要一次循环,依次比较之前的元素加当前元素(current+nums[i])和当前元素(nums[i])哪个大(因为会有负数存在)来决定是从当前元素开始加
    还是加上之前的元素
    然后比较current和之前最大的sum谁大

    6. Plus One:

    Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

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

    The digits are stored such that the most significant digit is at the head of the list.

    class Solution(object):
        def plusOne(self, digits):
            """
            :type digits: List[int]
            :rtype: List[int]
            """
            if len(digits)==1 and digits[0]==0:
                digits[0]=1
                return digits
            digits.reverse()
            cin=1
            for i in range(len(digits)):
                add=digits[i]+cin
                if add==10:
                    cin=1
                    digits[i]=0
                    if i==len(digits)-1:
                        digits.append(cin)
                else:
                    cin=0
                    digits[i]=add
            digits.reverse()
            return digits

    这道题有点类似于全加器的感觉,要有一个cin来决定是否进位,这里我用了一个小tricky的做法,就是先把数组全部reverse一下,这样就可以放心的从第一位开始加,最后再reverse回来就行了

    7. Merge Sorted Array:

    Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

    Note:
    You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

    class Solution(object):
        def merge(self, nums1, m, nums2, n):
            """
            :type nums1: List[int]
            :type m: int
            :type nums2: List[int]
            :type n: int
            :rtype: void Do not return anything, modify nums1 in-place instead.
            """
            for i in range(len(nums2)):
                nums1.append(nums2[i])
            nums1.sort()
            if m==0:
                nums1.remove(0)
            del_nums=len(nums1)-(m+n)
            if del_nums!=0:
                for i in range(0,del_nums):
                    nums1.remove(0)

    1)list.remove(x)只能移除list中和x相匹配的第一个元素,所以进行循环删除前面所有0

    2)0不算

    8. Pascal's Triangle:

    Given numRows, generate the first numRows of Pascal's triangle.

    For example, given numRows = 5,
    Return

    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]
    class Solution(object):
        def generate(self, numRows):
            """
            :type numRows: int
            :rtype: List[List[int]]
            """
            if numRows==0:
                return []
            result=[]
            result.append([1])
            if numRows==1:
                return result
            result.append([1,1])
            if numRows==2:
                return result
            
            for i in range(2,numRows):
                nums=[]
                nums.append(1)
                while len(nums)<i:
                    nums.append(result[i-1][len(nums)-1]+result[i-1][len(nums)])
                nums.append(1)
                result.append(nums)
            return result
                    
            

     这题没什么说的,就是按照pascal triangle的形成做的

    9. Pascal's Triangle II:

    Given an index k, return the kth row of the Pascal's triangle.

    For example, given k = 3,
    Return [1,3,3,1].

    class Solution(object):
        def getRow(self, rowIndex):
            """
            :type rowIndex: int
            :rtype: List[int]
            """
            result=[[1],[1,1]]
            if rowIndex==0:
                return result[0]
            if rowIndex==1:
                return result[1]
            
            for i in range(2,rowIndex+1):
                nums=[]
                nums.append(1)
                while len(nums)<i:
                    nums.append(result[i-1][len(nums)-1]+result[i-1][len(nums)])
                nums.append(1)
                result.append(nums)
            return result[rowIndex]

    10. Best Time to Buy and Sell Stock:

     Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            if not prices:
                return 0
            max_diff=0
            min_price=max(prices)
            for i in range(0,len(prices)):
                min_price=min(min_price,prices[i])
                max_diff=max(max_diff,prices[i]-min_price)
                
            return max_diff
    啊这道题被气死,本来觉得很简单,直接双层循环遍历整个list比较,一气呵成,结果提交的时候一长串的List会报time limit exceed的错误
    于是想尽办法优化,后来发现只需要在一层循环遍历,用min()和max()就行了


    11.
    Best Time to Buy and Sell Stock II

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            max_pro=0
            for i in range(0,len(prices)-1):
                if prices[i+1]>prices[i]:
                    max_pro+=prices[i+1]-prices[i]
                    
            return max_pro

    12. Two Sum II - Input array is sorted:

    Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    第一种做法:

    class Solution(object):
        def twoSum(self, numbers, target):
            """
            :type numbers: List[int]
            :type target: int
            :rtype: List[int]
            """
    #        result=[]
    #        if numbers==None:
    #            return []
    #        for i in range(0,len(numbers)-1):
    #            for j in range(1,len(numbers)):
    #                if i==j:
    #                    continue
    #                if numbers[i]+numbers[j]==target:
    #                    result.append(i+1)
    #                    result.append(j+1)
    #                    return result
            l=0
            r=len(numbers)-1
            while l<r:
                sum_num=numbers[l]+numbers[r]
                if sum_num==target:
                    return [l+1,r+1]
                elif sum_num<target:
                    l+=1
                elif sum_num>target:
                    r-=1

    第二种做法:

    class Solution(object):
        def twoSum(self, numbers, target):
            """
            :type numbers: List[int]
            :type target: int
            :rtype: List[int]
            """
            #dictionary algorithm
            result={}
            for i in range(len(numbers)):
                if target-numbers[i] in result:
                    return [result[target-numbers[i]]+1,i+1]
                else:
                    result[numbers[i]]=i
    1. solution1中注释掉的解法是我原来的解法,但是对于很长的List报了time limit exceed的错误
    2. solution1中最终的做法需要mark!因为这种算法很常见,two pointers,一个从头,一个从尾,while l<r是不相遇的条件这种算法复杂度低,所以不会报time limit exceed
    3. solution2中用的是字典的算法(来自discuss),字典的key是numbers里的元素,value是index。每次循环只需要去查找字典内的key有没有等于target-num[i]的,如果有,直接返回value+1,
    如果没有,把num[i]也作为key存入字典。很机智!

    13. Majority Element:

    Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

    You may assume that the array is non-empty and the majority element always exist in the array.

    class Solution(object):
        def majorityElement(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            result={}
            if len(nums)==1:
                return nums[0]
            for i in range(len(nums)):
                if nums[i] in result:
                    result[nums[i]]=result[nums[i]]+1
                    if result[nums[i]]>len(nums)/2:
                        return nums[i]
                else:
                    result[nums[i]]=1
    思路和之前有道题很像,就是存入字典,键是每个元素,值是个数

    14. Rotate Array:

    Rotate an array of n elements to the right by k steps.

    For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

    class Solution(object):
        def rotate(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            k = k%len(nums)
    
            nums[:] = nums[-k:]+nums[:-k]
            
    这道题真的。。很无语。。没有返回,只能在nums本身做修改
    要考虑两种情况,一种是k>len(nums)一种是k<len(nums),解决这一矛盾的方法就是k%len(nums),如果k<len(nums),则返回k,
    如果大于,返回余数
    还要注意[-k:]的意思是,从倒数第k(0开始)个元素到最后,[:-k]是从头到倒数第k个元素
     



     
    
    
     


  • 相关阅读:
    P4318 完全平方数 [二分答案+容斥+莫比乌斯函数]
    P2522 [HAOI2011]Problem b
    莫比乌斯反演学习笔记
    UVALive646 Deranged Exams [容斥+排列组合]
    HDU5514 Frogs [容斥(II)]
    P2567 [SCOI2010]幸运数字 [容斥+有技巧的搜索]
    微信api退款操作
    类中或者是程序集中,根据虚拟路径获取绝对路径
    加载程序集中内嵌资源
    .NET Framework 框架简述01
  • 原文地址:https://www.cnblogs.com/x1mercy/p/7820949.html
Copyright © 2020-2023  润新知