LeetCode-ArrayAndDigit

来源:互联网 发布:手游抢激活码软件 编辑:程序博客网 时间:2024/06/08 20:12

leetcode array

401.Binary Watch

二进制表。时针范围1-11,分针范围0-59。对时和分进行遍历,只要它们的二进制中的1的个数等于输入的个数,就把该时刻加入list

def readBinaryWatch( num):    """    :type num: int    :rtype: List[str]    """    result = []    for h in range(0,12):        for m in range(0,60):            if (bin(h)+bin(m)).count('1') == num:                result.append('%d:%02d'% (h,m))    return result 

1.TwoSum

求数组中两个数相加等于某个给出数target的索引

我的做法是,依次遍历,有相等的就加入list,用时较长

def twoSum(nums, target):    """    :type nums: List[int]    :type target: int    :rtype: List[int]    """    l = []    for i in range(0,len(nums)):        for j in range(i+1,len(nums)):            if(nums[i]+nums[j]==target):                l.append(i)                l.append(j)    return l

比较好的做法是,将数组中每个数和其索引存入dict中。然后遍历数组,如果target-n在dict中,就返回对应的两个索引。

def twoSum( nums, target):    """    :type nums: List[int]    :type target: int    :rtype: List[int]    """    hmap = {}    for i, n in enumerate(nums):        if n not in hmap:            hmap[n] = (i,)        else:            hmap[n] = (hmap[n][0], i)#有两数相同的情况    for n in nums:        if target - n in hmap:            if target - n == n and len(hmap[target - n]) == 1:#如果hmap[n]只有一个,那么无法返回两个索引,需要继续遍历                continue            return hmap[n][0], hmap[target - n][-1] #此处-1是取两数相同情况的后一个数

88. 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.        """        ## The key is to start comparing from the tails!!        while m > 0 and n > 0:            if nums1[m - 1] >= nums2[n - 1]:                nums1[m + n - 1] = nums1[m - 1]                m -= 1            else:                nums1[m + n - 1] = nums2[n - 1]                n -= 1        if n > 0:            nums1[:n] = nums2[:n]

118. Pascal’s Triangle

打印杨辉三角形

class Solution:    # @return a list of lists of integers    def generate(self, numRows):        ret = []        for i in range(numRows):            ret.append([1])            for j in range(1,i+1):                if j==i:                    ret[i].append(1)                else:                    ret[i].append(ret[i-1][j]+ret[i-1][j-1])        return retclass Solution(object):    def generate(self,numRows):        res = [[1]*i for i in range(1,numRows+1)]        for i in range(2,numRows):            for j in range(1,i):                res[i][j] = res[i-1][j-1] + res[i-1][j]        return res

119. Pascal’s Triangle II

打印杨辉三角形的指定行

class Solution:      # @return a list of integers      def getRow(self, rowIndex):          rownum=rowIndex+1          currow=[1]          if rownum==1:              return currow          if rownum>0:              currow=[1]              for index in range(rownum):                  prerow=currow                  currow=[1]                  for j in range(index-1):                      currow.append(prerow[j]+prerow[j+1])                  currow.append(1)          return currow  

167. Two Sum II - Input array is sorted

数组已经排好序。从两边往中间搜索的方法是

def twoSum(numbers, target):    """    :type numbers: List[int]    :type target: int    :rtype: List[int]    """    left,right = 0,len(numbers)-1    while left<right:        if numbers[left]+numbers[right]==target:            return [left+1,right+1]        elif numbers[left]+numbers[right]>target:            right= right-1        else:            left = left+1

用dict的方法:

def twoSum(numbers,target):    num_dict = {}    for i ,num in enumerate(numbers):        if (target-num) in num_dict:            return [num_dict[target-num],i+1]        num_dict[num] = i+1

122.BestTimetoBuyandSellStock II

给出每天价格表。返回经过这些天后所能获得的最大收益。基本思想是只要后一天比前一天的price高,就进行一次买卖。即差价>0,就说明利润大于0,依次累加即可。

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

136.Single Number

找出数组中唯一一个单独的数,快速的做法是利用异或与交换律
交换律a ^ b = b ^ a,性质2:0 ^ a = a。于是利用交换律可以将数组假想成相同元素全部相邻,于是将所有元素依次做异或操作, 相同元素异或为0,最终剩下的元素就为Single Number。时间复杂度O(n),空间复杂度O(1)

def singleNumber(nums):    """    :type nums: List[int]    :rtype: int    """    n = 0    for num in nums:        n = n ^ num    return n

我的做法是排序后遍历比较,超时了

def singleNumber(nums):    """    :type nums: List[int]    :rtype: int    """    nums = sorted(nums)    i=0    while(i<len(nums)):        if i+1<len(nums) and nums[i]==nums[i+1]:            i=i+2        else:            return nums[i]    return nums[-1]

169.MajorityElement

找出数组中的主元素。出现次数大于数组长度一般的数为主元素。简单的方法是排序后取1/2处的索引即可:

class Solution(object):    def majorityElement(self, nums):        nums.sort()        return nums[len(nums)//2]

我的方法很蠢:将元素个数存入字典,返回字典中值大于n(1/2长度)的数

def majorityElement(nums):    """    :type nums: List[int]    :rtype: int    """    n = len(nums)//2    num_dict = {}    for i in range(0,len(nums)):        if nums[i] not in num_dict:            num_dict[nums[i]] = 1        else:            num_dict[nums[i]]+=1    for i in num_dict:        if num_dict[i]>n:            return i

217.Contains Duplicate

检测数组中是否存在两个相同的数

def containsDuplicate(nums):    """    :type nums: List[int]    :rtype: bool    """    x = set(nums)    if len(x) == len(nums):        return False    else:        return True

258. Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

def addDigits(self, num):    """    :type num: int    :rtype: int    """    if num <= 9:        return num    elif num % 9 == 0:        return 9    else:        return num % 9

283.moveZeroes

将数组中的0移动到数组末尾

class Solution(object):    def moveZeroes(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """        i = 0        for num in nums:            if num != 0:                nums[i] = num                i += 1        for j in xrange(i, len(nums)):            nums[j] = 0

371.sumOfTwoIntegers

不用+求两个数的和

class Solution(object):    def getSum(self, a, b):        """        :type a: int        :type b: int        :rtype: int        """        return sum([a,b])class Solution(object):    def getSum(self, a, b):        if a == 0: return b        if b == 0: return a        neg_bit, mask = (1 << 32) >> 1, ~(~0 << 32)        a = (a | ~mask) if a<0 else (a & mask)        b = (b | ~mask) if b<0  < 0 else (b & mask)        while b:            carry = a & b            a = a ^ b            a = (a | ~mask) if (a & neg_bit)  else (a & mask)            b = carry << 1            b = (b | ~mask) if (b & neg_bit)  else (b & mask)        return a

447.numberOfBoomerangs

求给出点中的三个点,其中一个点到其他点距离相等的组合个数

# Example:# Input:# [[0,0],[1,0],[2,0]]## Output:# 2## Explanation:# The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]def numberOfBoomerangs(points):    """    :type points: List[List[int]]    :rtype: int    """    count = 0    for i in range(0,len(points)):        points_dict ={}        for j in range(0,len(points)):            distance =(points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) + (points[i][1] - points[j][1]) * (points[i][1] - points[j][1])            if distance not in points_dict:                points_dict[distance] = 0            count += points_dict[distance]*2            #由于 a,b,c 与a,c,b不同,所以一次要*2            points_dict[distance]+=1    return count

448.findDisappearedNumbers

找出1到 len(nums)中所有没在nums中的数

def findDisappearedNumbers(self, nums):    """    :type nums: List[int]    :rtype: List[int]    """    ret = set(range(1, len(nums) + 1))    ret = ret - set(nums)    return list(ret)def findDisappearedNumbers(self, nums):    """    :type nums: List[int]    :rtype: List[int]    """    l = len(nums)+1    nums = set(nums)    return [i for i in range(1, l) if i not in nums]

453.MinimumMovestoEqualArrayElements

对于一个长度为n的整型数数组,每步将n-1个元素加1,求最少需要多少步,能使数组中的数字全部相同。

因为每个数都会经历递增的过程,最后达到一个ceiling。假设数组元素最终为X,数组最小元素min需要经过X - min次增长,
最大元素max需要经过X - max次增长,(X - min) - (X - max) = max - min就是max不变
其余元素包括min增长的次数,经过这些次增长后,min元素和max元素大小相等,且它俩成为当前数组最小元素。
然后我们再让这俩最小元素增长到当前数组最大元素(初始数组次最大元素max2)的大小,增长的次数是max2 - min,
最终使得这三个元素相等。每一次增长都让数组中大小相同的元素增加一个,从1到2到3~~~n,
故总共增加了max - min, max2(初始数组次最大元素) - min, max3 - min,,,总和就是sum - min * n

class Solution(object):    def minMoves(self, nums):        """        :type nums: List[int]        :rtype: int        """        return sum(nums)-len(nums)*min(nums)

455.AssignCookies

给出每个孩子需求的饼干,与提供的饼干大小。使用贪心算法

def findContentChildren(g, s):    """    :type g: List[int]    :type s: List[int]    :rtype: int    """    #很容易想到,每个孩子尽量拿到和他想要的大小差距最小的饼干,    # 就能保证不会“浪费”大块饼干。因此把g和s排序后,把最相邻的饼干分给刚刚好满足的孩子    # ,就能得到最大的满足数量了。    g=sorted(g)    s=sorted(s)    count = 0    i,j=0,0    while j<len(s) and i<len(g):        if g[i]<=s[j]:            count+=1            i+=1        j+=1    return count

463.islandPerimeter

计算矩阵给出岛屿的边数,即岛屿周长。

def islandPerimeter(self, grid):    """    :type grid: List[List[int]]    :rtype: int    """    res = 0    for i in xrange(len(grid)):        for j in xrange(len(grid[i])):            if grid[i][j] == 1:·               #一个岛在不算邻居的情况下有4条边                res += 4                # Check Neighbor,只算左上即可,有邻居则各减一条边,所以总数减2                if i > 0 and grid[i - 1][j] == 1:                    res -= 2                if j > 0 and grid[i][j - 1] == 1:                    res -= 2    return res

475.heaters

给两个数组houses和heaters,houses表示房间放置的位置,heaters表示火炉放置的位置,求能火炉能温暖房间的最小半径
Example 1:

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

Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

Example 2:

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

Explanation: The two heater was placed in the position 1 and 4. We need to use

class Solution(object):#我的方法超时    def findRadius(self, houses, heaters):        """        :type houses: List[int]        :type heaters: List[int]        :rtype: int        """        res = 0        l = []        if len(houses)==1:            for i in heaters:                x = abs(i-houses[0])                res = min(res,x)            return res        for i in heaters:            if i in houses:                houses.remove(i)        for i in range(0,len(houses)):            minradius = 100000000000            for j in range(0,len(heaters)):                if houses[i]!=heaters[j]:                    ranges = abs(houses[i]-heaters[j])                    minradius = min(ranges,minradius)            l.append(minradius)        if l == []:            return 0        else:            return max(l)class Solution(object):    def findRadius(self, houses, heaters):        """        :type houses: List[int]        :type heaters: List[int]        :rtype: int        """        heaters = sorted(heaters) + [float('inf')]        i = 0        res = 0        for house in sorted(houses):            while heaters[i + 1] - house < house - heaters[i]:                i += 1            res = max(res, abs(heaters[i] - house))        return res

485.MaxConsecutiveOnes

给一个数组,判断出连续1的个数最多的数,比如例子中,有一个两个连续的1,有一个三个连续的1,则最大数为3.数组只包含0和1,数组内数字个数不会超过10000个.

def findMaxConsecutiveOnes( nums):    """    :type nums: List[int]    :rtype: int    """    maxlength = 0    length =0    for i in range(0,len(nums)):        if nums[i]==0:            length = 0        else:            length = length+1        if length>maxlength:            maxlength = length    return maxlength

496.NextGreaterElement

给定两个数组num1和num2,两个数组中的元素都是唯一的并且num1是num2的一个子集。求num1中的元素对应的num2中相同的元素在num2中右边第一个大于它的元素。

def nextGreaterElement(findNums, nums):    """    :type findNums: List[int]    :type nums: List[int]    :rtype: List[int]    """    n1 = list(findNums)    n2 = list(nums)    result = []    count = 0    for i in n1:        index = 0        for j in n2:            if (i==j)and(index!=len(n2)-1):                for x in n2[index+1:]:                    if x>i:                        count=1                        result.append(x)                        break            index = index+1        if count==0:            result.append(-1)        count = 0    return result

506.findRelativeRanks

给数组中元素排名,即把元素替换成相应排名,前三名用词组表示。

def findRelativeRanks(nums):    """    :type nums: List[int]    :rtype: List[str]    """    rank_dict={}    for i,k in enumerate(sorted(nums,reverse=True)):        rank_dict[k]=i+1    for i in range(0,len(nums)):        if rank_dict[nums[i]] == 1:            nums[i] = 'Gold Medal'        elif rank_dict[nums[i]] == 2:            nums[i] = 'Silver Medal'        elif rank_dict[nums[i]] == 3:            nums[i] = 'Bronze Medal'        else:            nums[i] = str(rank_dict[nums[i]])    return nums

598. Range Addition II

给定m * n矩阵M,初始为0,然后执行一些更新操作。

数组ops表示一组更新操作,每一个操作(a, b),表示将矩阵0 <= i < a 并且 0 <= j < b的区域值+1。

进行若干操作后,求矩阵的最大值的个数。

class Solution(object):    def maxCount(self, m, n, ops):        """        :type m: int        :type n: int        :type ops: List[List[int]]        :rtype: int        """        if not ops: return m * n        return min(op[0] for op in ops) * min(op[1] for op in ops)

628_MaximumProductofThreeNumbers

求三个数乘积最大,负最大也行

def maximumProduct(nums):    """    :type nums: List[int]    :rtype: int    """    nums = sorted(nums)    return max(nums[-1]*nums[-2]*nums[-3],nums[0]*nums[-1]*nums[-2],nums[0]*nums[1]*nums[2],nums[0]*nums[1]*nums[-1])

350.Intersection of Two Arrays II

求两个数组的交集,集合中每个元素出现的次数和两个集合中出现最小的次数一样。

# Example:# Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

我的做法是,求两个集合,若有元素两个数组都有,则取该元素次数较少的个数插入到所求list中

def intersect(nums1, nums2):    """    :type nums1: List[int]    :type nums2: List[int]    :rtype: List[int]    """    l = []    a= set(nums1)    b = set(nums2)    for i in a:        if i in b:            if nums1.count(i) >= nums2.count(i):                for j in range(0, nums2.count(i)):                    l.append(i)            else:                for j in range(0, nums1.count(i)):                    l.append(i)    return l

比较好的做法是将两个数组中出现过的元素均存储在字典中,然后对于h1中每一个元素k求 min(h1[k], h2.get(k, 0))即k的个数,*[k]代表形成list:

class Solution(object):    def intersect(self, nums1, nums2):        """        :type nums1: List[int]        :type nums2: List[int]        :rtype: List[int]        """        h1, h2, ret = {}, {}, []        for n in nums1:            h1[n] = h1.get(n, 0) + 1        for n in nums2:            h2[n] = h2.get(n, 0) + 1        for k in h1:            ret += [k] * min(h1[k], h2.get(k, 0))        return ret

599.MininumIndexSumOfTwoLists

找出两个数组中的字符串元素相同且索引相加最小的字符串

我的方法是依次遍历即可:

class Solution(object):    def findRestaurant(self,list1, list2):        """        :type list1: List[str]        :type list2: List[str]        :rtype: List[str]        """        l = []        miniSum = len(list1)+len(list2)-2        for i in range(0,len(list1)):            for j in range(0,len(list2)):                if list1[i]==list2[j]:                    tempSum = i+j                    if tempSum<miniSum:                        miniSum  = tempSum                        l=[]                        l.append(list1[i])                    elif tempSum == miniSum:                        l.append(list1[i])        return l

好一点的做法是,将字符串及对应索引存入dict,之后思路差不多,但是dict要更快:

def findRestaurant(list1, list2):    dic = {}    for i, s in enumerate(list1):        dic[s] = i    sol = []    min_sum = len(list1) + len(list2)    for i, s in enumerate(list2):        if s in dic:            this_sum = dic[s] + i            if this_sum < min_sum:                sol = [s]                min_sum = this_sum            elif this_sum == min_sum:                sol.append(s)    return sol

504. Base 7

十进制转7进制

def convertToBase7(self,num):    """    :type num: int    :rtype: str    """    s =''    if num>=0:        while num>=7:            s = str(num%7)+s            num = num//7        s = str(num)+s        return s    else:        num = -num        while num>=7:            s = str(num%7)+s            num = num//7        s = '-'+str(num)+s        return s

268.Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.

0到n(包括n,n为数组长度)中少了一个数,找出这个数
最好的做法是等差数列求和,然后减去给出数组的和

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

我的:

def missingNumber(nums):    """    :type nums: List[int]    :rtype: int    """    a = set(nums)    for i in range(0, len(nums) + 1):        if i not in a:            return i

605. Can Place Flowers

数组有花的位置记为1,无花记为0,现要往无花的位置栽花,并且花相邻必须是空的,即0,1,0 。 求所给数组是否能载下n盆花

贪心算法(Greedy Algorithm)

从左向右遍历flowerbed,将满足要求的0设为1。计数与n比较即可。

class Solution(object):    def canPlaceFlowers(self, flowerbed, n):        """        :type flowerbed: List[int]        :type n: int        :rtype: bool        """        ans = 0        for i, v in enumerate(flowerbed):            if v: continue            if i > 0 and flowerbed[i - 1]: continue            if i < len(flowerbed) - 1 and flowerbed[i + 1]: continue            ans += 1            flowerbed[i] = 1        return ans >= nclass Solution(object):    def canPlaceFlowers(self, flowerbed, n):        """        :type flowerbed: List[int]        :type n: int        :rtype: bool        """        placed = 0        m = len(flowerbed)        i = 0        while i < m - 1:            if flowerbed[i + 1] == 0:                if flowerbed[i] == 0:                    placed += 1                i += 2            else:                i += 3        if i < m and flowerbed[i] == 0:            placed += 1        return placed >= n

645.SetMismatch

找出数组1-n中,出现两次和没出现的

class Solution(object):    def findErrorNums(self, nums):        """        :type nums: List[int]        :rtype: List[int]        """        n = len(nums)        twice = sum(nums) - sum(set(nums))        miss = twice + n*(n+1)/2 - sum(nums)        return [twice, miss]class Solution(object):    def findErrorNums(self, nums):        """        :type nums: List[int]        :rtype: List[int]        """        ind = [0] * (len(nums)+1)        rep = 0        for e in nums:            if ind[e] != 1:                ind[e] = 1            else:                rep = e                break        org = (1 + len(nums)) * len(nums) / 2        mis = org - sum(nums) + rep        return [rep, mis]

121_BestTimetoBuyandSellStock

只能买卖一次

class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        if len(prices) == 0 or len(prices) == 1:            return 0        MAX = 0        start = prices[0]        for price in prices:            if price - start > MAX:                MAX = price - start            if price < start :                start = price        return MAX

594.LongestHarmoniousSubsequence

We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Example 1:

Input: [1,3,2,2,5,2,3,7]

Output: 5

Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Note: The length of the input array will not exceed 20,000.
我的超时了

def findLHS(nums):""":type nums: List[int]:rtype: int"""maxlength = 0a  = set(nums)for i in a:    if nums.count(i-1)!=0 or nums.count(i+1)!=0:        left = nums.count(i)+ nums.count(i-1)        right = nums.count(i)+ nums.count(i+1)        if left>=right:            if maxlength<left:                maxlength=left        else:            if maxlength<right:                maxlength = rightreturn maxlengthprint(findLHS([1,3,2,2,5,2,3,7]))class Solution(object):    def findLHS(self, nums):        """        :type nums: List[int]        :rtype: int        """        count = collections.Counter(nums)        ans = 0        for x in count:            if x+1 in count:                ans = max(ans, count[x] + count[x+1])        return ansclass Solution(object):    def findLHS(self, nums):        """        :type nums: List[int]        :rtype: int        """        a = 0        dict = {}        for i in nums:            if i not in dict:                dict[i] = 1            else:                dict[i] += 1        return max([dict[i] + dict[i + 1] for i in dict if i + 1 in dict] or [0])

202.HappyNumber

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

12 + 92 = 82

82 + 22 = 68

62 + 82 = 100

12 + 02 + 02 = 1

class Solution(object):    def isHappy(self, n):        """        :type n: int        :rtype: bool        """        def helper(n):            ans = 0            while n > 0:                ans = ans + (n % 10) ** 2                n = n // 10            return ans        s = set()        while n != 1:            if n in s:                return False            else:                s.add(n)                n = helper(n)        return True

326. Power of Three

判断一个数是否是3的幂次,不用循环和递归

class Solution(object):def isPowerOfThree(self, n):    """    :type n: int    :rtype: bool    """    return n > 0 and (1162261467 % n == 0)import mathclass Solution(object):    def isPowerOfThree(self, n):        """        :type n: int        :rtype: bool        """        if n <= 0:            return False        tmp = math.log(n, 3)        return 3 ** round(tmp, 0) == n

70. Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

当有n个台阶时,可供选择的走法可以分两类:1,先跨一阶再跨完剩下n-1阶;2,先跨2阶再跨完剩下n-2阶。所以n阶的不同走法的数目是n-1阶和n-2阶的走法数的和。
这个时候如果用递归,复杂度会太大而无法AC,所以用动态规划记录历史数据,即可。

class Solution(object):    def climbStairs(self, n):        """        :type n: int        :rtype: int        """        if n == 0 or n == 1 or n == 2:            return n        steps = [1, 1]        for i in xrange(2, n+1):            steps.append(steps[i-1] + steps[i-2])        return steps[n]

当输入为1, 2, 3, 4, 5, 6, 7, 8, 9, 10时,观察输出为1, 2, 3, 5, 8, 13, 21, 34, 55, 89,是斐波那契数列!
class Solution(object):
def climbStairs(self, n):
“””
:type n: int
:rtype: int
“””
pre = cur = 1
for i in xrange(1, n):
pre, cur = cur, pre+cur
return cur

35.Search Insert Position

返回targrt的索引,找不到就插入合适位置再返回索引

def searchInsert(nums, target):    """    :type nums: List[int]    :type target: int    :rtype: int    """    if target in nums:        return nums.index(target)    else:        nums.append(target)        nums = sorted(nums)        return nums.index(target)class Solution(object):    def searchInsert(self, nums, target):        i = len(nums)/2        min_possible = 0        max_possible = len(nums)        while max_possible != min_possible:            if nums[i] > target:                max_possible = i                i -= (i + 1 - min_possible) / 2            elif nums[i] < target:                min_possible = i + 1                i += (max_possible + 1 - i) / 2            else:                return i        return min_possible

53.maxSubArray

求最大连续子串

我的超时

def maxSubArray(nums):#超时    """    :type nums: List[int]    :rtype: int    """    maxSum= max(nums)    for i in range(0,len(nums)):        for j in range(i+1,len(nums)):            k = sum(nums[i:j])            if sum(nums[i:j+1])>maxSum:                maxSum = sum(nums[i:j+1])    return maxSum

用max_sum表示最终结果,this_sum表示目前最大的和。基本思想是,如果sum>=0,就可以和A[i]拼接在一起构成新的sum’。因为不管A[i]多大,加上一个正数总会更大
一旦子串小于0,就从新的位置开始求和(因为加上一个负数只会更小)
class Solution(object):
def maxSubArray(self, nums):
“””
:type nums: List[int]
:rtype: int
“”“

        max_sum = nums[0]        this_sum = 0        cache = 0        for num in nums:            this_sum += num            if this_sum > max_sum:                max_sum = this_sum            if this_sum <= 0:                this_sum = 0        return max_sumclass Solution {  public:      int maxSubArray(int A[], int n) {          int max_sum = INT_MIN;          int sum = INT_MIN;          for (int i = 0; i < n; ++i) {              if (sum < 0) sum = 0;              sum += A[i];              if (sum > max_sum)                  max_sum = sum;          }          return max_sum;      }  };  

27.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 in place with constant memory.

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

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

class Solution(object):def removeElement(self, nums, val):    """    :type nums: List[int]    :type val: int    :rtype: int    """    while (val in nums):        nums.remove(val)def removeElement(self, nums, val):    index = 0    for num in nums:        if num != val:            nums[index] = num            index += 1    return indexclass Solution(object):    def removeElement(self, nums, val):        """        :type nums: List[int]        :type val: int        :rtype: int        """        if nums == []:            return 0        else:            front = 0            back = len(nums) - 1            while (front <= back):                if nums[front] == val:                    temp = nums[front]                    nums[front] = nums[back]                    nums[back] = temp                    back -= 1                else:                    front += 1        nums = nums[0:front]        return front

198.House Robber

给定数组表示一组房子里放的现金,要求不能偷相邻的两间房子。求偷得最大金额

比如:[3,2,6,4,5]。偷3,6,5.最大金额为14

此题用动态规划,递推公式为

robbest[i] = max(robbest[i - 1], nums[i - 2] + robbest[i - 2])

robbest[i]表示偷第i间房子能获得的最大金额

class Solution(object):    def rob(self, nums):        """        :type nums: List[int]        :rtype: int        """        #if len(nums)==0:        #    return 0        best=[0,0]        #best.append(nums[0])        for i in range(len(nums)):            best.append(max(nums[i]+best[-2],best[-1]))        return best[-1]class Solution(object):    def rob(self, nums):        """        :type nums: List[int]        :rtype: int        """        robbest = [0] * (len(nums) + 2)        for i in xrange(2, len(nums) + 2):            robbest[i] = max(robbest[i - 1], nums[i - 2] + robbest[i - 2])        return robbest[-1]

643. Maximum Average Subarray I

求平均值最大的连续子串,使用动态规划。
我的超时了
def findMaxAverage(nums, k):
“””
:type nums: List[int]
:type k: int
:rtype: float
“””
maxsum = 0
for i in range(0,len(nums)):
if i+k<=len(nums) and sum(nums[i:i+k])> maxsum :
maxsum = sum(nums[i:i+k])
return maxsum/k

先计算连续四个数的和。当计算到第5个数时,减去第1个,加上第5个,求和并且与之前存的sum进行比较,取较大值赋值给sum

class Solution(object):    def findMaxAverage(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: float        """        sum = 0        curSum = 0        addNum = 0        for i in range(0, len(nums)):            if addNum < k:                curSum += nums[i]                sum = curSum                addNum += 1            else:                curSum = curSum - nums[i - k] + nums[i]                sum = max(sum, curSum)        return sum * 1.0 / k

66.plus one

给出一个非负的数,用数组来表示这个数,比如说9999就是[9,9,9,9]当对这个数加一的时候,将这个数用数组的形式返回。

我的:

def plusOne(digits):    """    :type digits: List[int]    :rtype: List[int]    """    l = []    s = ''    for i in digits:        s = s + str(i)    digit = int(s)    digit +=1    for i in str(digit):        l.append(int(i))    return l

最快的:

class Solution(object):    def plusOne(self, digits):        """        :type digits: List[int]        :rtype: List[int]        """        if not digits: return [1]        carry = 1        for i in xrange(len(digits) - 1, -1, -1):            val = digits[i] + carry            if val == 10:                carry = 1                digits[i] = 0            else:                carry = 0                digits[i] = val        if carry: digits = [1] + digits        return digits