学习计划剑指offer: 第四天

114 阅读1分钟

数组中重复的数字

找出数组中重复的数字。

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

输入:
[2, 3, 1, 0, 2, 5, 3]
输出: 23 

限制:

2 <= n <= 100000

leetcode-cn.com/problems/sh…

class Solution {
    public int findRepeatNumber(int[] nums) {
        for(int i=0; i<nums.length; i++){
            while(nums[i]!=i){
                if(nums[nums[i]] == nums[i]) return nums[i];
                int temp = nums[i];
                nums[i] = nums[temp];
                nums[temp] = temp;
            }
        }
        return -1;
    }
}

在排序数组中查找数字 I

统计一个数字在排序数组中出现的次数。

输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0

提示:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • nums 是一个非递减数组
  • -109 <= target <= 109

leetcode-cn.com/problems/za…

class Solution {
    public int search(int[] nums, int target) {
        if(nums.length ==0){
            return 0;
        }

        int left =0;
        int right = nums.length-1;
        int index =-1;
        while(left <=right){
            int mid = left + (right-left) /2;
            if(nums[mid] > target){
                right = mid -1;
            } else if(nums[mid] < target){
                left = mid +1;
            } else {
                index = mid;
                break;
            }
        }

        if(left >=0 && left < nums.length && nums[left] ==target){
            index = left;
        }
        if(right >=0  && right < nums.length && nums[right] ==target){
            index = right;
        }

        if(index == -1){
            return 0;
        }
        left = index;
        right = index +1;
        int sum =0;
        while (( left >=0 && nums[left] == target) || (right < nums.length && nums[right] == target)){
            if(( left >=0 && nums[left] == target)){
                sum++;
                left--;
            }
             if((right <=nums.length-1 && nums[right] == target)){
                sum++;
                right++;
            }
        }
        return sum;
    }
}

0~n-1中缺失的数字

一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。

输入: [0,1,3]
输出: 2
输入: [0,1,2,3,4,5,6,7,9]
输出: 8

leetcode-cn.com/problems/qu…

class Solution {
    public int missingNumber(int[] nums) {
        int left =0;
        int right = nums.length-1;
        while(left <right){
            int mid = left + (right-left) /2;
            if(nums[mid] != mid){
                right = mid;
            } else {
                left = mid +1;
            } 
        }
            return left == nums.length - 1 && nums[left] == left ? left + 1 : left;

    }
}