lintcode刷题(python)(1)

来源:互联网 发布:js 获取object类型 编辑:程序博客网 时间:2024/06/04 18:34

友情提示,可以将上面的目录展开以便查找相应题目。吐舌头

1.将整数A转换为B(flip bits)

如果要将整数A转换为B,需要改变多少个bit位?

 注意事项

Both n and m are 32-bit integers.

class Solution:    """    如果要将整数A转换为B,需要改变多少个bit位?    @param a, b: Two integer    return: An integer        如把31转换为14,需要改变2个bit位。    (31)10=(11111)2    (14)10=(01110)2    """    def bitSwapRequired(self, a, b):        # 当a和b为1和-1时,python二进制为0b1和-0b1,和预计的31不符,要转化为没有负号的形式。        if a<0:            a=2**32+a        if b<0:            b=2**32+b        a = str(bin(a)).replace("0b", "")        b = str(bin(b)).replace("0b", "")        sum = 0        if len(a) > len(b):            for i in range(0, len(a) - len(b)):                b = "0" + b        else:            for i in range(0, len(b) - len(a)):                a = "0" + a        for i in range(0, len(a)):            if a[i] != b[i]:                sum += 1        return sumsolution=Solution()print(solution.bitSwapRequired(1,-1))


2.最大子数组

给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

 注意事项

子数组最少包含一个数

样例

给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6

解析:使用贪心算法。

class Solution:    """    @param nums: A list of integers    @return: An integer denote the sum of maximum subarray    """    def maxSubArray(self, nums):        '''        思路:一个个遍历数组并累加,结果大于0则保留,小于0则舍弃        如果数组中全为负数,则找出最大的负数                '''        #如果数组长度为1,直接返回        if len(nums)==1:            return nums[0]        currentMax=0    #永远是当前的最大值        Sum=0  # 遍历数组,累加值        for i in range(0,len(nums)):            Sum+=nums[i]            if Sum<0:                Sum=0   # 如果Sum<0,则重置为0            if Sum>currentMax:                currentMax=Sum #当遍历时累加值大于currentMax,则更新它        #要考虑数组中全为负数的情况,如果全为负数,直接返回其中最大的        allMinus=True        for i in nums:            if i>0:                allMinus=False                break        if allMinus:            return max(nums)        return currentMaxsolution=Solution()print(solution.maxSubArray([-2,2,-3,4,-1,2,1,-5,3]))

之前还自己硬写了一个算法,也能返回正确结果,不过不满足时间复杂度,也贴上来参考一下吧。。

class Solution:    """    @param nums: A list of integers    @return: An integer denote the sum of maximum subarray    """    def maxSubArray(self, nums):        # write your code here        maxSum=nums[0]        Sum=0        if len(nums)==1:            return nums[0]        for i in range(0,len(nums)):            Sum=nums[i]            if nums[i]>maxSum:                maxSum=nums[i]            for j in range(i+1,len(nums)):                Sum+=nums[j]                if Sum>maxSum:                    maxSum=Sum        return maxSumsolution=Solution()print(solution.maxSubArray([-2,2,-3,4,-1,2,1,-5,3]))

3.合并区间 (merge intervals)

给出若干闭合区间,合并所有重叠的部分。

样例

给出的区间列表 => 合并后的区间列表:

[                     [  [1, 3],               [1, 6],  [2, 6],      =>       [8, 10],  [8, 10],              [15, 18]  [15, 18]            ]]

代码如下,写的很烂,有空再改进吧。。

"""Definition of Interval.class Interval(object):    def __init__(self, start, end):        self.start = start        self.end = end"""class Solution:    # @param intervals, a list of Interval    # @return a list of Interval    def merge(self, intervals):        # write your code here results=[]        equalResults=[]  # [3,3]存3就行了        originalList=[]        for i in intervals:            if i.start==i.end and i .start not in equalResults:                equalResults.append(i.start)            else:                for j in range(i.start,i.end):                    originalList.append(j)        middleList=sorted( list (set(originalList)))        for i in equalResults:            if i not in originalList:                results.append([i,i])        start = middleList[0]        for i in range(0,len( middleList)-1):            if middleList[i+1]- middleList[ i ]>1:                results.append([start,middleList[i ]+1])                start=middleList[ i +1]            if i==len( middleList)-2:                results.append([start,middleList[i+ 1]+1])                        for i in results:            if i[0]==i[1]:                for j in results:                    if j[0]!=j[1]:                        if j[0] <=i[0] and i [0]<=j[1]:                            results.remove(i)                            break        #去重去两遍                            for i in results:            if i[0]==i[1]:                for j in results:                    if j[0]!=j[1]:                        if j[0] <=i[0] and i [0]<=j[1]:                            results.remove(i)                            break        return sorted(results)


4.矩阵的之字型遍历 

给你一个包含 m x n 个元素的矩阵 (m 行, n 列), 求该矩阵的之字型遍历。

样例

对于如下矩阵:

[  [1, 2,  3,  4],  [5, 6,  7,  8],  [9,10, 11, 12]]

返回 [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12]

class Solution:    # @param: a matrix of integers    # @return: a list of integers    def printZMatrix(self, matrix):        # 在遍历的时候,有一个明显的特点,斜着的的横坐标加上纵坐标等于某一个相同值,且最小为0,最大为横纵长度之和-2(totalLength)。        # 第二个特点,当和为奇数时,往左下方遍历,当和为偶数时,向右上方遍历。        result=[]        if matrix==[]:            return []        # write your code here        lenX = len(matrix[0])        lenY = len(matrix)        if lenX==0 or lenY==0:            return []        totalLengh = lenX + lenY - 2        for singleTotal in range(0, totalLengh+1):            if singleTotal%2!=0:                for j in range(0,lenY):                    for i in range(0,lenX):                        if (i+j)==singleTotal:                            result.append(matrix[j][i])                            break            else:                for i in range(0,lenX):                    for j in range(0,lenY):                        if (i+j)==singleTotal:                            result.append(matrix[j][i])                            break        return result

5.搜索二维矩阵 

写出一个高效的算法来搜索 m × n矩阵中的值。

这个矩阵具有以下特性:

  • 每行中的整数从左到右是排序的。
  • 每行的第一个数大于上一行的最后一个整数。
样例

考虑下列矩阵:

[  [1, 3, 5, 7],  [10, 11, 16, 20],  [23, 30, 34, 50]]

给出 target = 3,返回 true


class Solution:    """    @param matrix, a list of lists of integers    @param target, an integer    @return a boolean, indicate whether matrix contains target    """    def searchMatrix(self, matrix, target):        #一行一行遍历二维矩阵,先与该行中最后一个数比较,如果大于该数直接跳过该行,如果小于该数还可能在该行中。        for i in matrix:            for j in i:                if target > i[len(matrix[0]) - 1]:                    break                if j==target:                    return True        return Falsesolution=Solution()print(solution.searchMatrix([  [1, 3, 5, 7],  [10, 11, 16, 20],  [23, 30, 34, 50]],20))

搜索二维矩阵 II 

写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。

这个矩阵具有以下特性:

  • 每行中的整数从左到右是排序的。
  • 每一列的整数从上到下是排序的。
  • 在每一行或每一列中没有重复的整数。
样例

考虑下列矩阵:

[

    [1, 3, 5, 7],

    [2, 4, 7, 8],

    [3, 5, 9, 10]

]

给出target = 3,返回 2

class Solution:    """    @param matrix: An list of lists of integers    @param target: An integer you want to search in matrix    @return: An integer indicates the total occurrence of target in the given matrix    """    def searchMatrix(self, matrix, target):        # write your code here        count=0        for i in matrix:            for j in i:                if target==j:                    count+=1        return count



整数排序 II 

给一组整数,按照升序排序。使用归并排序,快速排序,堆排序或者任何其他 O(n log n) 的排序算法。

样例

给出 [3, 2, 1, 4, 5], 排序后的结果为 [1, 2, 3, 4, 5]

不想再写排序算法了。。直接sort带走

不过要强调的一点是不能使用sorted方法!!

sort()与sorted()的不同在于,sort是在原位重新排列列表,而sorted()是产生一个新的列表,也就是说会复制一份A出来,对于这道题目是不正确的。

class Solution:    # @param {int[]} A an integer array    # @return nothing    def sortIntegers2(self, A):        # Write your code here        A.sort()          


字符大小写排序 

给定一个只包含字母的字符串,按照先小写字母后大写字母的顺序进行排序。

 注意事项

小写字母或者大写字母他们之间不一定要保持在原始字符串中的相对位置。

样例

给出"abAcD",一个可能的答案为"acbAD"

这道题和上一道异曲同工 ,都使用了sort排序,不过这个使用了lambda表达式。

class Solution:    """    @param chars: The letters array you should sort.    """    def sortLetters(self, chars):        # write your code here        chars.sort(key=lambda c: c.isupper())

买卖股票的最佳时机 

假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

样例

给出一个数组样例 [3,2,3,1,2], 返回 1 

class Solution:    """    @param prices: Given an integer array    @return: Maximum profit    """    def maxProfit(self, prices):        #使用贪心算法,遍历数组,maxProfit当前的最大利益,minBuyPrice代表当前买入的最小价格        #如果遍历过程中发现有最小买入价格,则更新minBuyPrice;如果发现有最大利益,则更新maxProfit        if len(prices)==0 or len(prices)==1:            return 0        # write your code here        maxProfit=0        minBuyPrice=prices[0]        for i in range(1,len(prices)):            TodayPriceMinusMinBuyPrice=prices[i]-minBuyPrice            if minBuyPrice > prices[i]:                minBuyPrice = prices[i]            if TodayPriceMinusMinBuyPrice>maxProfit:                maxProfit=TodayPriceMinusMinBuyPrice        return maxProfit


落单的数 

给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。

样例

给出 [1,2,2,1,3,4,3],返回 4


class Solution:    """    @param A : an integer array    @return : a integer    """    def singleNumber(self, A):        # 先考虑A为空数组和只有一个数的情况。        if A==[]:            return 0        if len(A)==1:            return A[0]                # 将A排序,使数组变得整洁。        A.sort()        # 其余情况,要判断第一个数与最后一个数是不是落单数。剩下的就是在中间找了。        if A[0]!=A[1]:            return A[0]        for i in range(1,len(A)-1):            if A[i]!=A[i-1] and A[i]!=A[i+1]:                return A[i]        if A[len(A)-1]!=A[len(A)-2]:            return A[len(A)-1]solution=Solution()print(solution.singleNumber([1,2,2,1,3,4,3]))


落单的数 II 

给出3*n + 1 个的数字,除其中一个数字之外其他每个数字均出现三次,找到这个数字。

给出 [1,1,2,3,3,3,2,2,4,1] ,返回 4

代码和上一题一模一样,没错。。因为原理是一样的,即使是4*n+1、100*n+1,依然是一模一样的代码。。

落单的数 III 

给出2*n + 2个的数字,除其中两个数字之外其他每个数字均出现两次,找到这两个数字。

给出 [1,2,2,3,4,4,5,3],返回 1和5

思路和上面还是差不多的。只是上面如果找到落单的数,直接返回就行了。在本题中,先新建一个result列表,如果找到落单的数,把它放到列表中,遍历完数组后,返回result即可。

class Solution:    """@param A : An integer array@return : An integer    """    def singleNumberII(self, A):        # write your code here        if A==[]:            return 0        if len(A)==2:            return A        result=[]        A.sort()        if A[0] != A[1]:            result.append(A[0])        for i in range(1, len(A) - 1):            if A[i] != A[i - 1] and A[i] != A[i + 1]:                result.append(A[i])        if A[len(A) - 1] != A[len(A) - 2]:            result.append(A[len(A) - 1])        return result


主元素 

给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。


 注意事项

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

给出数组[1,1,1,1,2,2,2],返回 1

class Solution:    """    @param nums: A list of integers    @return: The majority number occurs more than 1/2    """    def majorityNumber(self, nums):        # 先把这个数组去重,得到singleElementList。        # 对于每个元素,计算出现的次数,如果大于长度1/2,直接返回该元素。        cishu = int(len(nums) / 2)        singleElementList = list(set(nums))                for i in singleElementList:            sum = 0            for j in nums:                if j == i:                    sum += 1                    if sum > cishu:                        return j        return None


主元素 II 

给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。


 注意事项

数组中只有唯一的主元素

给出数组[1,2,1,2,1,3,3] 返回 1

    和上面的思路一样,只要把除以2的地方改成3即可,so easy。。。。


寻找缺失的数 

给出一个包含 0 .. N 中 N 个数的序列,找出0 .. N 中没有出现在序列中的那个数。

N = 4 且序列为 [0, 1, 3] 时,缺失的数为2

class Solution:    # @param nums: a list of integers    # @return: an integer    def findMissing(self, nums):        # 先将nums排序,如果该序列中间缺少某个数,就会被检测出来        # 如果没有被检测出来,则返回该数组的长度。即最后一个数+1        nums.sort()        for i in range(0,len(nums)):            if i != nums[i]:                return i        return len(nums)

最长公共子串

给出两个字符串,找到最长公共子串,并返回其长度。



子串的字符应该连续的出现在原字符串中,这与子序列有所不同。

给出A=“ABCD”,B=“CBCE”,返回 2

class Solution:    # @param A, B: Two string.    # @return: the length of the longest common substring.    def longestCommonSubstring(self, A, B):        # example:A=“ABCD”,B=“CBCE”, maxLength=2        # 对A进行遍历 遍历出所有子序列,如果子序列在B中也存在,那么计算子序列长度。        # 返回最大长度        maxLength=0        for i in range(0,len(A)):            for j in range(i+1,len(A)+1):                slice=A[i:j]                if slice in B and len(slice)>maxLength:                    maxLength=len(slice)        return maxLength



0 0
原创粉丝点击