python homework——the eighth week

本文探讨了数组操作中的三种典型算法问题:求两个数组的交集、检查数组是否能通过修改一个元素变为非递减数组、查找数组中消失的数字。通过对这些问题的分析,介绍了使用哈希表来优化算法复杂度的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

349.Intersection of two arrays

Given two arrays, write a function to compute their intersection.

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

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

class Solution():
def intersection(self, nums1, nums2):
"""
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
"""
nums3=[]
for num1 in nums1:
for num2 in nums2:
if num1==num2 and num1 not in nums3:
nums3.append(num1)
return nums3

思路:这道题最简单粗暴的解法是把一个数组的每一个元素跟另一个数组的每一个元素做比较,如果相等的且不在第三数组的就放进第三数组中。最后第三个数组就是两个数组的交集

代码:


    但是这种解法复杂度为O(n^2),明显太高。如果采用哈希的方法就可以将复杂度减少为O(n)。定义一个哈希函数,每一个元素值对应哈希表中的一个位置,并把哈希表先初始化为全0;先遍历数组一,将其中出现的元素对应的哈希表的元素加一,再遍历数组二,将其中出现的元素对应的哈希表的元素加一;最后遍历哈希表,如果元素值为2,则用其索引还有哈希函数(index = hash(ele))推出数组一和数组二的一个公共值,最后所有这些公共值组成数组一二的交集。设哈希表大小为N,则复杂度仅为O(n)


665.Non_decreasing array

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most1 element.

We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).

思路:这道题我的解法是先判断n是否小于3,如果是则直接返回True;如果不是,则先遍历整个数组,可能是否有减小的地方,若没有,直接返回True,若有,则采用一种简单粗暴的方法:遍历数组中前n-1个元素,比如遍历到第i个元素,将他赋值为下一个元素的值,然后对整个数组做一次检查,看还有没有减小的地方,如果没有就返回True,如果有,继续到下一个元素,重复上次的操作。如果到第n-1个元素仍然没有返回,就将最后一个元素赋值为前一个元素的值,再对整个数组进行检查,看是否还有减小的地方。这种方法复杂度为O(n^2)

class Solution:
def checkPossibility(self,nums):
if len(nums)<3:
return True
if check(nums):
return True
else:
for i in range(0,len(nums)-1):
tmp=nums[i]
nums[i]=nums[i+1]
if check(nums):
return True
else:
nums[i]=tmp
nums[len(nums)-1]=nums[len(nums)-2]
if check(nums):
return True
return False


def check(nums):
flg=0
for i in range(1,len(nums)):
if nums[i]<nums[i-1]:
flg=1
break
if flg==0:
return True
else:

return False


448.Find all numbers disappeared in an array

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

思路:这道题也是用哈希的方法。另设一个数组listd(大小跟要处理的数组nums相同),将其初始化为[1,2,3,...,n],遍历nums,若出现了num,就将listd[num-1]赋值为0。最后再开一个数组,将listd中不为0的数都添加进来,即得到不在nums中的数的集合

class Solution:
def findDisappearedNumbers(self,nums):
listd=[]
list1=[]
for i in range(1,len(nums)+1):
listd.append(i)
for num in nums:
listd[num-1]=0
for num in listd:
if num!=0:
list1.append(num)
return list1



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值