1.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?
解题思路:
假设传入的列表为 nums = [2, 3, 1, 5, 0]。
首先,在 nums 的末尾 append 一个负整数例如-1,(只要和列表其它元素不重复即可),此时 nums = [2, 3, 1, 0, 5, -1],列表的长度 length 为6。
接下来,对列表的元素从 nums[0] 到 nums[length-2] 进行遍历(即对原列表遍历)。每个元素遍历后,取该元素的值的绝对值为下标,对列表相应的元素进行取相反数操作。
例如:
第一次遍历,i = 0,nums[0] = 2,再对nums[nums[0]]取相反数,得新列表为[2, 3, -1, 0, 5, -1]。
第二次遍历,i = 1,nums[1] = 3,再对nums[3]取相反数,得新列表为[2, 3, -1, 0, 5, -1]。
第三次遍历,i = 2,nums[2] = -1,再对nums[1]取相反数,得新列表为[2, -3, -1, 0, 5, -1]。
第四次遍历,i = 3,nums[3] = 0, 再对nums[0]取相反数,得新列表为[-2, -3, -1, 0, 5, -1]。
第五次遍历,i = 4,nums[4] = 5, 再对nums[5]取相反数,得新的列表为[-2, -3, -1, 0, 5, 1]。
此时得到一个新的列表[-2, -3, -1, 0, 5, 1]。
接下来进入判断:
对列表最后一个元素(额外添加的元素)进行判断,如果为1,则表示原列表存在元素5(对nums[5]取相反数才能得到1);若为-1,则表示原列表缺失的元素是5。
再对列表进行进行从 nums[0] 到 nums[length -2] 遍历,如果有nums[i] 为正数,则说明该列表缺失的元素为 i (因为列表不存在元素 i ,使得对 nums[i] 取相反数)。
最后,如果 nums[0] 到nums[length-2] 无正数,则返回 nums[0] 的下标。(因为对0取相反数还是0)。
代码如下:
import math class Solution: def missingNumber(self, nums): nums.append(-1); length = len(nums) for i in range(0, length-1): nums[int(math.fabs(nums[i]))] *= -1 if nums[length-1] == -1: return length-1 else: for i in range(0, length-1): if nums[i] > 0: return i for i in range(0, length-1): if nums[i] == 0: return i
2.Max Consecutive Ones
题目概述:
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Note:
- The input array will only contain
0
and1
. - The length of input array is a positive integer and will not exceed 10,000
解题思路:
题目要求统计最长的“1”的长度,但如果直接统计连续的“1”,则需要进行多重循环和判断,这样会大大降低效率。
倒不如换一个思路:记录“0”出现的位置,则相邻的两个“0”之间的都是个“1”,相减即可得到连续的“1”的长度,这样能将时间复杂度降低到O(n)。
在对列表进行“0”判断时,要先进行一些处理:对原列表的头部和尾部各增加一个“0”,以使得任意两个相邻的“0”的位置相减就可
代码如下:
class Solution: def findMaxConsecutiveOnes(self, nums): nums.insert(0, 0) nums.append(0) maxDistance = 0 lastZero = 0 for i in range(1, len(nums)): if nums[i] == 0: if maxDistance < i - lastZero - 1: maxDistance = i - lastZero - 1 lastZero = i return maxDistance