剑指offer3:数组中重复的元素
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
解题思路:
利用哈希表记录数组的数字,新建 HashSet ,遍历数组 nums 中的每个数字 num :
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int repeat = -1;
for(int num : nums){
if(!set.add(num)) {
repeat = num;
break;
}
}
return repeat;
}
}
剑指offer53-I:在排序数组中查找数字I
统计一个数字在排序数组中出现的次数。
解题思路:so easy
大家说面试出这个是考二分/(ㄒoㄒ)/~~
class Solution {
public int search(int[] nums, int target) {
int count = 0;
for(int i = 0;i < nums.length;i++){
if(nums[i] == target)
count++;
}
return count;
}
}
剑指offer53-II:0~n-1中缺失的数字
一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。
解题思路:
还是想遍历,大家说天天遍历offer都遍历到别人手里去了,还是要二分/(ㄒoㄒ)/~~
so~ 就是一种妙妙妙的算法:理论和减实际和就是缺失的数字!!!!!
class Solution {
public int missingNumber(int[] nums) {
int sum = nums.length * (nums.length+1)/2;
return sum - Arrays.stream(nums).sum();
}
}