leetcode - 刷题记录-探索初级算法-数组

  1. 从排序数组中删除重复项:
    1. 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
    2. class Solution(object):
          def removeDuplicates(self, nums):
              """
              :type nums: List[int]
              :rtype: int
              """
              if len(nums)<2:
                  return len(nums)
              else:
                  i = 0
                  j = 1
                  while 1:
                      while j<len(nums) and i<len(nums) and nums[j]<=nums[i]: 
                          j += 1
                      if j==len(nums) or i == len(nums) :
                          break
                      else:
                          i += 1
                          nums[i],nums[j] = nums[j],nums[i]
                          j += 1
                          #print(i,j,nums)
                  return i+1
                  

      通过

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

    1. 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

      设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

      注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

    2. class Solution:
          def maxProfit(self, prices: List[int]) -> int:
              
              buy = 0
              sold = 0
              res = 0
              while buy < len(prices):
                  while sold<len(prices)-1 and prices[sold+1] > prices[sold]:
                      sold += 1
                  res += prices[sold] - prices[buy]
                  #print(buy,sold,res)
                  buy = sold + 1
                  sold = buy
              return res

      通过

  3. 旋转数组

    1. 给定一个数组,将数组中的元素向右移动 个位置,其中 是非负数。

    2. class Solution(object):
          def right(self, nums, k, l ):
              print('right')
              for i in range(k):
                  nums.extend(nums)
                  del nums[:-(l+1)]
                  del nums[-1]
                  
          def left(self, nums, k, l):
              print('left')
              l = len(nums)
              for i in range(k):
                  nums.extend(nums)
                  del nums[0]
                  del nums[l:]        
                  
          def rotate(self, nums, k):
              """
              :type nums: List[int]
              :type k: int
              :rtype: None Do not return anything, modify nums in-place instead.
              """
              l = len(nums)
              k = k%l
              if k < 0.5*l:
                  self.right(nums, k, l)
              else:
                  self.left(nums, l-k, l)

      通过

  4. 存在重复

    1. 给定一个整数数组,判断是否存在重复元素。

      如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

    2. class Solution(object):
          def containsDuplicate(self, nums):
              """
              :type nums: List[int]
              :rtype: bool
              """
              if len(nums) <= 1:
                  return False
              else:
                  res = []
                  i = 0
                  j = len(nums)-1
                  while i < j:
                      if nums[i] == nums[j]:
                          return True
                      elif nums[i] in res or nums[j] in res:
                          return True
                      else:
                          res.extend([nums[i],nums[j]])
                          i += 1
                          j -= 1
                  return False

      17/18通过测试用例,不知道如何优化。哭哭

    3. class Solution:
          def containsDuplicate(self, nums: List[int]) -> bool:
              dic = {}
              for i in range(len(nums)):
                  if nums[i] in dic:
                      return True
                  else:
                      dic[nums[i]]=i
              return False

      通过了,用了哈希就行。。。不是什么复杂问题!!!

  5. 只出现一次的数字

    1. 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

    2. class Solution(object):
          def singleNumber(self, nums):
              """
              :type nums: List[int]
              :rtype: int
              """        
              while len(nums) >= 1:
                  tmp = nums[0]
                  if tmp in nums[1:]:
                      nums.remove(tmp)
                      nums.remove(tmp)
                  else:
                      break
              return nums[0]

      通过

  6.  两个数组的交集 II

    1. 给定两个数组,编写一个函数来计算它们的交集。

    2. class Solution(object):
          def intersect(self, nums1, nums2):
              """
              :type nums1: List[int]
              :type nums2: List[int]
              :rtype: List[int]
              """
              n1 = nums1 if len(nums1) < len(nums2) else nums2
              n2 = nums2 if len(nums1) < len(nums2) else nums1
              res = []
              for i in n1:
                  if i in n2:
                      res.append(i)
                      n2.remove(i)
              return res

      通过

  7. 加一

    1. 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。

      最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。

      你可以假设除了整数 0 之外,这个整数不会以零开头。

    2. class Solution(object):
          def plusOne(self, digits):
              """
              :type digits: List[int]
              :rtype: List[int]
              """
              res = []
              flag = 0
              for i in range(len(digits),0,-1):
                  if i == len(digits):
                      flag = 1 if digits[i-1] + 1 == 10 else 0
                  else :
                      flag = 1 if digits[i-1] + flag == 10 else 0
                  
                  digits[i-1] = 0 if flag == 1 else digits[i-1] + 1
                  
                  if flag == 0:
                      break
              if flag == 1:
                  digits = [1]+digits
              return digits

      通过

  8. 移动零

    1. 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

      1. 必须在原数组上操作,不能拷贝额外的数组。
      2. 尽量减少操作次数。
    2. class Solution(object):
          def moveZeroes(self, nums):
              """
              :type nums: List[int]
              :rtype: None Do not return anything, modify nums in-place instead.
              """
              
              x = nums.count(0)
              for i in range(x):
                  indx = nums.index(0)
                  for j in range(indx,len(nums)-1):
                      nums[j] = nums[j+1]
                  nums[-1] = 0
              return nums

      通过

  9. 两数之和

    1. 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

      你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

    2. class Solution:
          def twoSum(self, nums: List[int], target: int) -> List[int]:
              # bad
              for i in range(len(nums)-1):
                  sub = nums[i+1:]
                  res_sub = [j+nums[i] for j in sub]
                  if target in res_sub:
                      return [i,i+res_sub.index(target)+1]
              # hashmap
              dic = {}
              for i,n in enumerate(nums):
                  if target-n in dic:
                      return [dic[target-n],i]
                  else:
                      dic[n]=i
                      

      通过

  10. 有效的数独

    1. 判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。

      数字 1-9 在每一行只能出现一次。数字 1-9 在每一列只能出现一次。数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
    2. class Solution:
          def isValidSudoku(self, board: List[List[str]]) -> bool:
              dic_row = {}
              dic_col = {}
              dic_block = {}
              for i in range(9):
                  # row
                  for j in range(9):
                      # column
                      if board[i][j] == '.':
                          continue
                          
                      if i not in dic_row:
                          dic_row[i] = [board[i][j]]
                      else:
                          if board[i][j] in dic_row[i]:
                              return False
                          else:
                              dic_row[i].append(board[i][j])
                              
                      if j not in dic_col:
                          dic_col[j] = [board[i][j]]
                      else:
                          if board[i][j] in dic_col[j]:
                              return False
                          else:
                              dic_col[j].append(board[i][j])
                              
                      if 10*int(i/3)+int(j/3) not in dic_block:
                          dic_block[10*int(i/3)+int(j/3)] = [board[i][j]]
                      else:
                          if board[i][j] in dic_block[10*int(i/3)+int(j/3)]:
                              return False
                          else:
                              dic_block[10*int(i/3)+int(j/3)].append(board[i][j])
                          
              return True

      通过。有些code中,不止思路重要,选择合适的数据格式也很重要。

发布了45 篇原创文章 · 获赞 1 · 访问量 8564

猜你喜欢

转载自blog.csdn.net/qq_32110859/article/details/104266335