【leetcode】Array_Easy

1.Two Sum
#mine,循環(huán)相加
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為標(biāo)記推進(jìn)
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
#其實(shí)就是算有多少個比他小的
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
#從第一個開始算颅崩,如果為負(fù)數(shù)或和為負(fù)數(shù)就記下當(dāng)前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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市话侧,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌闯参,老刑警劉巖瞻鹏,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件悲立,死亡現(xiàn)場離奇詭異,居然都是意外死亡新博,警方通過查閱死者的電腦和手機(jī)薪夕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來赫悄,“玉大人原献,你說我怎么就攤上這事」』矗” “怎么了姑隅?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長倔撞。 經(jīng)常有香客問我讲仰,道長,這世上最難降的妖魔是什么痪蝇? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任鄙陡,我火速辦了婚禮,結(jié)果婚禮上霹俺,老公的妹妹穿的比我還像新娘柔吼。我一直安慰自己,他們只是感情好丙唧,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布愈魏。 她就那樣靜靜地躺著,像睡著了一般想际。 火紅的嫁衣襯著肌膚如雪培漏。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天胡本,我揣著相機(jī)與錄音牌柄,去河邊找鬼。 笑死侧甫,一個胖子當(dāng)著我的面吹牛珊佣,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播披粟,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼咒锻,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了守屉?” 一聲冷哼從身側(cè)響起惑艇,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后滨巴,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體思灌,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年恭取,在試婚紗的時候發(fā)現(xiàn)自己被綠了泰偿。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡秽荤,死狀恐怖甜奄,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情窃款,我是刑警寧澤课兄,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站晨继,受9級特大地震影響烟阐,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜紊扬,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一蜒茄、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧餐屎,春花似錦檀葛、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至藏鹊,卻和暖如春润讥,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背盘寡。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工楚殿, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人竿痰。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓脆粥,卻偏偏與公主長得像,于是被迫代替她去往敵國和親影涉。 傳聞我的和親對象是個殘疾皇子冠绢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容