leetcode 287
Posted 热之雪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 287相关的知识,希望对你有一定的参考价值。
287. Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input:[1,3,4,2,2]
Output: 2Example 2:
Input: [3,1,3,4,2] Output: 3
观察序列可知,数组的最大的index肯定大于数组内的数,例如第一个例子中,index最大为4,而数组内最大数为4,则num[num[index]]肯定在数组内循环;
所以有1-3-2-【4-2】其中42构成环;用快慢指针可以解环的问题。
O(1)空间,O(n)时间
int findDuplicate3(vector<int>& nums) { if (nums.size() > 1) { int slow = nums[0]; int fast = nums[nums[0]]; while (slow != fast) { slow = nums[slow]; fast = nums[nums[fast]]; } fast = 0; while (fast != slow) { fast = nums[fast]; slow = nums[slow]; } return slow; } return -1; }
//取该数组的中间值mid,如果遍历数组发现所有大于mid的个数比mid大,证明重复的数字在右半区间,否则在左区间;以此类推。
//O(1)空间,O(nlogn)时间
calss Solution{ int findDuplicate(vector<int>& nums) { int n=nums.size()-1; int low=1; int high=n; int mid; while(low<high){ mid=(low+high)/2; int count=0; for(int num:nums){ if(num<=mid) count++; } if(count>mid) high=mid; else low=mid+1; } return low; } }
238. Product of Array Except Self
Given an array
nums
of n integers where n > 1, return an arrayoutput
such thatoutput[i]
is equal to the product of all the elements ofnums
exceptnums[i]
.Example:
Input:[1,2,3,4]
Output:[24,12,8,6]
Note: Please solve it without division and in O(n).不能使用除法和时间度O(n)
class Solution { vector<int> productExceptSelf(vector<int> nums) { int n = nums.size(); vector<int> res(n,1); for (int i = 1; i < n; i++) { res[i] = res[i - 1] * nums[i - 1]; //res数组从index=1开始保存nums[i-1]前所有数的乘积,即除了当前数的外前面的数的乘积 } int right = 1; for (int i = n - 1; i >= 0; i--) { res[i] *= right; right *= nums[i]; ///重复上面的过程,不过这次是从nums右边开始乘积;综合两次的乘积就能得出除了当前位置的左边乘积呈上右边乘积的res } return res; }
//举个例子
nums = 1, 2, 3, 4
res = 1, 1, 2, 6 //红的2是nums的1*2,从左到右
right = 24,12, 4, 1 //蓝的12是nums的3*4,从右到左
res = 24,12, 8, 6 //上面的两者叠乘就等于目标结果,即除去当前的值其他所有值的乘积
以上是关于leetcode 287的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 287 Find the Duplicate Number寻找重复数
[JavaScript 刷题] 双指针 - leetcode 142 & leetcode 287