leetcode 数组:简单题 第三页

122.买卖股票的最佳时机2

每当遇到一个价格的时候做出不同的判断即可

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        have_stock = 0
        total_profit = 0
        this_cur_profit = 0
        for price in prices:
            if not have_stock:
                buy_price = price
                have_stock = 1
            else:
                if price <= buy_price:
                    buy_price = price
                else:
                    total_profit += price - buy_price
                    buy_price = price
        return total_profit

27.移除元素

解法一:
运用python的remove()函数

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        n = len(nums) -1
        while n >= 0  :
            while len(nums) > 0 and nums[n] == val:
                nums.remove(nums[n])
                n -= 1
            n -= 1
        return len(nums)

解法二:双指针,分别从两个方向开始遍历。

1184.公交站间的距离

比较简单,之前看数据结构的时候做过类似题目

class Solution:
    def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
        cur_distance = 0
        if start > destination:
            start,destination = destination,start
        for i in range(start,destination):
            cur_distance += distance[i]
        return min(cur_distance,sum(distance)-cur_distance)

448. 找到所有数组中消失的数字

题目要求就地修改,不能使用额外的空间,因此可以通过两次遍历实现:第一次遍历通过坐标元素正负标记是否出现过,第二次遍历找出未出现过的元素。

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        for i in range(len(nums)):
            nums[abs(nums[i]) - 1] = -abs(nums[abs(nums[i]) - 1])
        ans = []
        for j in range(len(nums)):
            if nums[j] > 0:
                ans.append(j+1)
        return ans

485.最大连续1的个数

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        ans = 0
        cur_ans = 0
        for num in nums:
            if num == 1:
                cur_ans += 1
            else:cur_ans = 0
            ans = max(cur_ans,ans)
        return ans

268.缺失数字

数学公式求和再减去数组和即可

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n = len(nums)
        add = n *(n+1)//2
        return add-sum(nums)

1013.将数组分成和相等的三个部分

class Solution:
    def canThreePartsEqualSum(self, A: List[int]) -> bool:
        if sum(A) % 3 != 0:
            return False
        average = sum(A)//3
        cur_sum = 0
        index = len(A)
        for i in range(len(A)):
            cur_sum += A[i]
            if average == cur_sum:
                cur_sum = 0
                index = i
                break
        index2 = len(A)
        for j in range(index + 1,len(A)):
            cur_sum += A[j]
            if average == cur_sum:
                index2 = j
                break
        if index2 < len(A)-1:
            return True
        return False

1331.数组序号转换

tips:字典只表示一一对应关系的时候index和元素是可以互换位置的。

class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        dic = {}
        L = sorted(list(set(arr)))
        for i in range(len(L)):
            dic[L[i]] = i+1
        return [dic[arr[j]] for j in range(len(arr))] 

167.两数之和2-输入有序数组

双指针,充分利用所给的数组为有序数组这一条件

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        i,j = 0,len(numbers)-1
        while numbers[i] + numbers[j] != target:
            if numbers[i] + numbers[j] > target:
                j -= 1
            else:
                i += 1
        return [i+1,j+1]

661.图片平滑器

加注释那行的代码注意掌握,也是遍历列表的一种方式

class Solution:
    def imageSmoother(self, M: List[List[int]]) -> List[List[int]]:
        row,col = len(M),len(M[0])
        ans = [[0]*col for _ in range(row)]
        for i in range(row):
            for j in range(col):
                count = 0
                for nr in [i-1,i,i+1]:#遍历列表的一种方式
                    for nc in [j-1,j,j+1]:
                        if 0 <= nr < row and 0<=nc < col:
                            count += 1
                            ans[i][j] += M[nr][nc]
                ans[i][j] = int(ans[i][j] / count)
        return ans

121.买股票的最佳时机

数组+动态规划

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = float('inf')
        max_profit = 0
        for price in prices:
            if price < min_price:
                min_price = price
            elif price - min_price > max_profit:
                max_profit = price - min_price
        return max_profit

888.公平的糖果交换

解法一:两个有序数列做差的时候要按相同的顺序遍历
虽然写起来很长,但是复杂度与解法二是一样的。

class Solution:
    def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
        A,B = sorted(A),sorted(B)
        sum_A,sum_B = sum(A),sum(B)
        give_number = abs(sum_A-sum_B) // 2
        if sum_A < sum_B:
            i,j = 0,0
            while B[j] - A[i] != give_number:
                if B[j] - A[i] > give_number:
                    i += 1
                else: j += 1
            return [A[i],B[j]]
        else:
            i,j = 0,0
            while A[i] - B[j] != give_number:
                if A[i] - B[j] > give_number:
                    j += 1
                else: i += 1
            return [A[i],B[j]]

解法二:
直接运用数学公式化简:

697.数组的度

运用字典存储某元素的第一个和最后一个。

class Solution:
    def findShortestSubArray(self, nums: List[int]) -> int:
        left,right, count = {}, {}, {}
        for i in range(len(nums)):
            if nums[i] not in left:
                left[nums[i]] = i
            right[nums[i]] = i
            count[nums[i]] = count.get(nums[i], 0) + 1
        ans = len(nums)
        degree = max(count.values())
        for x in count:
            if count[x] == degree:
                ans = min(ans, right[x] - left[x] + 1)

        return ans

217.存在重复元素

哈希表存储

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        Hash = {}
        for num in nums:
            if num not in Hash:
                Hash[num] = 1
            else:
                Hash[num] += 1
        for value in Hash:
            if Hash[value] > 1:
                return True
        return False

896.单调数列

将相邻两个元素的关系转换为-1,0,1,之后判断是否均同号即可

class Solution:
    def isMonotonic(self, A: List[int]) -> bool:
        for i in range(len(A)-1):
            if A[i] > A[i+1]:
                A[i] = 1
            elif A[i] == A[i+1]:
                A[i] = 0
            else:A[i] = -1
        A.pop()
        index = 0
        for num in A:
            if num > 0 and index == 0:
                index = 1
            elif num < 0 and index == 0:
                index = -1
            
            if index < 0 and num > 0:
                return False
            if index > 0 and num < 0:
                return False
        return True

1275.找出井字棋的获胜者

建议删除这个题,只有麻烦方法,代码已通过

class Solution:
    def tictactoe(self, moves: List[List[int]]) -> str:
        movesA = [[0]*3 for _ in range(3)]
        movesB = [[0]*3 for _ in range(3)]
        for step in range(len(moves)):
            if step % 2 == 0:
                movesA[moves[step][0]][moves[step][1]] = 1
            else:
                movesB[moves[step][0]][moves[step][1]] = 1
        for i in range(3):
            if movesA[0][i] + movesA[1][i] + movesA[2][i] == 3:
                return 'A'
            elif movesB[0][i] + movesB[1][i] + movesB[2][i] == 3:
                return 'B'
            elif movesA[i][0] + movesA[i][1] + movesA[i][2] == 3:
                return 'A'
            elif movesB[i][0] + movesB[i][1] + movesB[i][2] == 3:
                return 'B'
        if movesA[0][0] + movesA[1][1] + movesA[2][2] == 3 or movesA[0][2] + movesA[1][1] + movesA[2][0] == 3:
            return 'A'
        if movesB[0][0] + movesB[1][1] + movesB[2][2] == 3 or movesB[0][2] + movesB[1][1] + movesB[2][0] == 3:
            return 'B'
        if len(moves) == 9:
            return 'Draw'
        else:return 'Pending'

1232.缀点成线

挺简单的思路,一次遍历即可。

class Solution:
    def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
        n = len(coordinates)
        distact = [0] * (n-1)
        for i in range(n-1):
            if coordinates[i+1][0]-coordinates[i][0] == 0:
                distact[i] = float('inf')
                continue
            distact[i] = (coordinates[i+1][1] - coordinates[i][1])/(coordinates[i+1][0]-coordinates[i][0])
            if i == 0:continue
            if distact[i] != distact[i-1]:
                return False
        return True

你可能感兴趣的:(leetcode 数组:简单题 第三页)