今天做了数组类的这几道题(287,268,136,1021,1014,905)这几道题中有的是实在想不出来参考了其他人的解法,也有完全自己想出来的,有些虽然是easy的题,但仍想不出好的解决方法,通过这几道题感觉学到了许多,感觉还是需要整理与回顾一下。
首先来看下这两道题,对时间复杂度或是空间复杂度都有严格的要求:
136. Single Number
题目描述:
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
解题思路:
需要在线性时间和不使用额外的的内存完成。也就是说不能申请新的数组或其他数据结构来计数了。这道题主要是采用位运算来完成,异或运算是相同位异或结果位0,而不同位异或结果为1,利用这个特性,我们可以找出数组的Single Number。因为数组中只有一个数是只出现了一次,而其他数都出现了两次。那么出现了两次的数异或结果肯定为0,因此遍历一遍数组,将所有元素做异或操作,最后得到的数就是那个只出现了一次的数。
代码如下;
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if not nums:
return None
res = 0
for num in nums:
res ^= num
return res
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.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
这道题同样的需要在线性的时间复杂度,并且是要求是常数的空间复杂度完成。
解题思路:
这个数组中的元素很有特点, 是不重复并且是0,1,2,3,...n数组长度是(n)。看到这道题首先想到的是声明一个长度为(n+1)的数组,用数组中的元素做下标来标记,最后就可以知道某一个下标没有标记的就是漏掉的数。但这样空间复杂度为O(n),不是常数。因此这种方法肯定不行,然后想到0,1,2,3...n序列数的和是固定的,遍历一边数组,减去数组的所有元素,最后剩下的数就是0-n之间漏的数。
代码如下:
class Solution:
def missingNumber(self, nums: List[int]) -> int:
if not nums:
return None
n = len(nums) +1
n_nums = len(nums)
sums = int((n*n_nums)/2) #等差数列求和:sn = n(a0+an)/2
#print(sums)
for i in nums:
sums -= i
return sums
剩下的题目请看[leetcode]数组类题目总结与回顾(287,1014)