【leetcode】Array_Easy

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

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

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)

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<target])

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

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

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()

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

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]

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

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])

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      

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

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]

217. Contains Duplicate
class Solution:
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        return len(nums)!=len(set(nums))

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

268. Missing Number
class Solution:
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return len(nums)*(len(nums)+1)//2-sum(nums)

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

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]

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]

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')))

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)

561. Array Partition I
class Solution:
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sum(sorted(nums)[::2])

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)]

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)

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])

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])

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

661. Image Smoother

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,137评论 6 511
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,824评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,465评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,131评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,140评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,895评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,535评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,435评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,952评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,081评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,210评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,896评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,552评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,089评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,198评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,531评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,209评论 2 357

推荐阅读更多精彩内容