第一题:41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0] Output: 3
Example 2:
Input: [3,4,-1,1] Output: 2
Example 3:
Input: [7,8,9,11,12] Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
如果不是限制O(n)的时间复杂度,可以先进行排序再去一个个寻找最小不见了的数,但有了这个限制只能用另外的方法。由于只能使用常数的额外空间,容易想到的是在原数组上进行修改。比如:通过下标表达的信息,把数值为i的值交换放到第i-1个数组元素里。这样可以通过一次遍历交换,再一次遍历找到与下标不对应的值,那就是要输出的答案。但由于有第三个例子,这样做可能会出现一个数组越界的问题。于是可以开一个数组大小为10000的列表在其中放入找到的正数,然后再一次遍历找最小丢失的正数就行了。代码如下
class Solution: def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ length=len(nums) maxi=10000 a=[value*0 for value in range(1,maxi+1)] for i in range(0,length): if nums[i]>0: a[nums[i]-1]=1 for i in range(0,len(a)): if a[i]==0: return i+1 return max(nums,default=0)+1
第二题:70. Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
由例子可以看出每个input对应的方案都可以分为先走一步,走剩下的n-1步和先走2步,走剩下的n-2步来做。这就是一个斐波那数列的问题了。可以通过递归或者数列的方法来完成。一开始我使用递归的时候,发现会出现time limit,于是改用数组和循环来做就accepted了,代码如下
class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ nums=[] nums.append(1) nums.append(2) for i in range(2,10000): nums.append(nums[i-1]+nums[i-2]) return nums[n-1]
这一题是给定四个点的坐标确定他们能否构成一个正方形。我的思路就是记录下它们4个点之间的互相6个距离,而如果能构成正方形,那么必定有4个一样的距离0和2个一样的距离1.再按照这样来判断就能知道它能不能构成一个正方形了。当然如果距离有0的话,一定构不成。而且如果不是有0的话,在二维空间里,四个点互相距离至少有两种情况。故代码不会在特殊情况出错也不会出现越界问题。代码如下:
class Solution(object): def validSquare(self, p1, p2, p3, p4): """ :type p1: List[int] :type p2: List[int] :type p3: List[int] :type p4: List[int] :rtype: bool """ test=[] test.append(dis(p1,p2)) test.append(dis(p1,p3)) test.append(dis(p1,p4)) test.append(dis(p2,p3)) test.append(dis(p2,p4)) test.append(dis(p3,p4)) if 0 in test : return False a=test[0] counter0=0 counter1=0 while a in test: test.remove(a) counter0+=1 a=test[0] while a in test: test.remove(a) counter1+=1 if((counter0==2 and counter1==4) or (counter0==4 and counter1==2)) : return True return False def dis(p1,p2): return (p1[0]-p2[0])**2+(p1[1]-p2[1])**2