【leetcode】Array_Easy

【leetcode】Array_Easy_第1张图片
1.Two Sum
#mine,循环相加
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j]==target:
                    return [i,j]
#discussion,字典存差
class Solution(object):
    def twoSum(self, nums, target):
        if len(nums) <= 1:
            return False
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return [buff_dict[nums[i]], I]
            else:
                buff_dict[target - nums[i]] = I

【leetcode】Array_Easy_第2张图片
26.Remove Duplicates from Sorted Array
#要求在nums上修改,返回截取的长度,以tail为标记推进
class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==0:
            return 0
        tail=0
        for i in range(len(nums)):
            if nums[tail]==nums[I]:
                continue
            else:
                tail+=1
                nums[tail]=nums[I]
        return tail+1

【leetcode】Array_Easy_第3张图片
27.Remove Element
#remove()移除第一个匹配到的元素
class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        try:
            while True:
                nums.remove(val)
        except:
            return len(nums)

【leetcode】Array_Easy_第4张图片
35. Search Insert Position
#其实就是算有多少个比他小的
class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        return len([x for x in nums if x

【leetcode】Array_Easy_第5张图片
53. Maximum Subarray
#从第一个开始算,如果为负数或和为负数就记下当前max然后重记
class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        mMax=nums[0]
        mSum=0
        for val in nums:
            mSum+=val
            mMax=max(mMax,mSum)
            mSum=max(mSum,0)
        return mMax

【leetcode】Array_Easy_第6张图片
66.Plus One
class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        return list(map(int,list(str(int(''.join(map(str,digits)))+1))))
        #for a very long data
        # digits[-1]+=1
        # tail=-1
        # while digits[tail]==10:
        #     digits[tail]=0
        #     if tail==-len(digits):
        #         digits.insert(0,1)
        #         break
        #     tail-=1
        #     digits[tail]+=1
        # return digits

【leetcode】Array_Easy_第7张图片
88. Merge Sorted Array
class Solution:
    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.
        """
        nums1[m:]=nums2
        nums1.sort()

【leetcode】Array_Easy_第8张图片
118. Pascal's Triangle
def generate(self, numRows):
        res = [[1]]
        for i in range(1, numRows):
            res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]
        return res[:numRows]
    1 3 3 1 0 
 +  0 1 3 3 1
 =  1 4 6 4 1

【leetcode】Array_Easy_第9张图片
119. Pascal's Triangle II
class Solution:
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        res=[[1]]
        for i in range(rowIndex):
            res+=[[x+y for x,y in zip(res[-1]+[0],[0]+res[-1])]]
        return res[-1]

【leetcode】Array_Easy_第10张图片
121. Best Time to Buy and Sell Stock
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max_profit=0
        min_price=float('inf')
        for price in prices:
            min_price=min(price,min_price)
            profit=price-min_price
            max_profit=max(profit,max_profit)
        return max_profit

【leetcode】Array_Easy_第11张图片
122. Best Time to Buy and Sell Stock II
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices)<2:
            return 0
        profits=map(lambda x,y:x-y,prices[1:],prices[:-1])
        return sum([x if x>0 else 0 for x in profits])

【leetcode】Array_Easy_第12张图片
167. Two Sum II - Input array is sorted
#用字典存差值
class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        dictMinus={}
        for i in range(len(numbers)):
            if numbers[i] in dictMinus:
                return [dictMinus[numbers[i]]+1,i+1]
            dictMinus[target-numbers[i]]=i      

【leetcode】Array_Easy_第13张图片
169. Majority Element
class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dictCount={}
        for num in nums:
            if num in dictCount:
                dictCount[num]+=1
            else:
                dictCount[num]=1
            if dictCount[num]>len(nums)//2:
                return num

【leetcode】Array_Easy_第14张图片
189. Rotate Array
class Solution:
    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]

【leetcode】Array_Easy_第15张图片
217. Contains Duplicate
class Solution:
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        return len(nums)!=len(set(nums))

【leetcode】Array_Easy_第16张图片
219. Contains Duplicate II
class Solution:
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dictSame={}
        for i in range(len(nums)):
            if (nums[i] in dictSame) and i-dictSame[nums[i]]<=k:
                return True
            else:
                dictSame[nums[i]]=I
        return False

【leetcode】Array_Easy_第17张图片
268. Missing Number
class Solution:
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return len(nums)*(len(nums)+1)//2-sum(nums)

【leetcode】Array_Easy_第18张图片
283. Move Zeroes
class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        c=0
        while True:
            try:
                nums.remove(0)
                c+=1
            except:
                nums+=[0]*c
                break

【leetcode】Array_Easy_第19张图片
414. Third Maximum Number
class Solution:
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        v=[float('-inf')]*3
        for n in nums:
            if n not in v:
                if n>v[0]:v[:]=[n,v[0],v[1]]
                elif n>v[1]:v[:]=[v[0],n,v[1]]
                elif n>v[2]:v[:]=[v[0],v[1],n]
        return v[0] if float('-inf') in v else v[-1]

【leetcode】Array_Easy_第20张图片
448. Find All Numbers Disappeared in an Array
class Solution:
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for num in nums:
            index = abs(num) - 1
            nums[index] = -abs(nums[index])
        return [i + 1 for i, num in enumerate(nums) if num > 0]

【leetcode】Array_Easy_第21张图片
485. Max Consecutive Ones
class Solution:
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return max(map(len,''.join(map(str,nums)).split('0')))

【leetcode】Array_Easy_第22张图片
532. K-diff Pairs in an Array
class Solution:
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        c = collections.Counter(nums)
        if k<0:
            return 0
        elif k==0:
            return sum(v>1 for v in c.values())
        elif k>0:
            return sum(v+k in c for v in c)

【leetcode】Array_Easy_第23张图片
561. Array Partition I
class Solution:
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sum(sorted(nums)[::2])

【leetcode】Array_Easy_第24张图片
566. Reshape the Matrix
class Solution:
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        flat=sum(nums,[])
        if c*r!=len(flat):
            return nums
        return [flat[x*c:x*c+c] for x in range(r)]

【leetcode】Array_Easy_第25张图片
581. Shortest Unsorted Continuous Subarray
class Solution:
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        is_same=[x==y for x,y in zip(nums,sorted(nums))]
        return 0 if all(is_same) else len(nums)-is_same[::-1].index(False)-is_same.index(False)

【leetcode】Array_Easy_第26张图片
605. Can Place Flowers
class Solution:
    def canPlaceFlowers(self, flowerbed, n):
        """
        :type flowerbed: List[int]
        :type n: int
        :rtype: bool
        """
        xixi=''.join(map(str,[0]+flowerbed+[0])).split('1')
        return n<=sum([(len(x)-1)//2 for x in xixi if x])

【leetcode】Array_Easy_第27张图片
628. Maximum Product of Three Numbers
class Solution:
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1])

【leetcode】Array_Easy_第28张图片
643. Maximum Average Subarray I
class Solution:
    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """
        newSum=maxSum=sum(nums[:k])
        for i in range(len(nums)-k):
            newSum=newSum-nums[i]+nums[I+k]
            if newSum>maxSum:
                maxSum=newSum
        return maxSum/k

【leetcode】Array_Easy_第29张图片
661. Image Smoother

你可能感兴趣的:(【leetcode】Array_Easy)