剑指 Offer 03. 数组中重复的数字
https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
- 使用额外空间存储不重复元素,遍历数组,如果遇到重复的则返回
- 代码如下:
使用了Set集合存储数据,也可以使用Map
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> numberSet = new HashSet<>();
for(int i=0;i<nums.length;i++){
if(!numberSet.add(nums[i])){
return nums[i];
}
}
return -1;
}
}
- 官方思路:原地置换。一个萝卜一个坑。空间复杂度降为O(1)
- 代码如下:
while循环每次把当前位置数字作为下标和当前下标内的数字交换,直到全部归位或者出现交换的数值相等的情况。
class Solution {
public int findRepeatNumber(int[] nums) {
int temp;
for(int i=0;i<nums.length;i++){
//如果元素和下标值不相等,说明没有顺序排列,开始跟以元素为下标的数值交换
while(nums[i]!=i){
//如果当前元素和要交换的元素相等,说明有重复数据,直接返回。
if(nums[i]==nums[nums[i]]){
return nums[i];
}
temp = nums[i];
nums[i] = nums[temp];
nums[temp] = temp;
}
}
return -1;
}
}
剑指 Offer 53 - I. 在排序数组中查找数字 I
https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
- 数组是有序的,循环遍历遇到大于target的即退出,时间复杂度O(N)
- 代码如下:
class Solution {
public int search(int[] nums, int target) {
int res =0;
for(int i=0;i<nums.length;i++){
if(nums[i]>target)
return res;
if(nums[i]==target)
res +=1;
}
return res;
}
}
- 二分查找,时间复杂度为O(logN)
- 代码如下:
class Solution {
public int search(int[] nums, int target) {
return helper(nums,target)-helper(nums,target-1);
}
public int helper(int[] nums, int target){
int i=0,j=nums.length-1;
while(i<=j){
int m = (i+j)/2;
if(nums[m]<=target){
i= m+1;
}else{
j = m-1;
}
}
return i;
}
}
剑指 Offer 53 - II. 0~n-1中缺失的数字
https://leetcode-cn.com/problems/que-shi-de-shu-zi-lcof/
1.主要实现也是二分法,如果中间元素和下标的值相等说明左边的元素都在自己的对应的下标上,向右查找,如果不等于,说明但当前坐标缺失对应元素被下一位占据,向左查移动的下标数值即为缺失元素值
class Solution {
public int missingNumber(int[] nums) {
int i=0,j=nums.length-1;
while(i<=j){
int m = (i+j)/2;
if(nums[m]==m) i=m+1;
else j= m-1;
}
return i;
}
}
浙公网安备 33010602011771号