😁算法小白欢迎加入此社区:https://bbs.csdn.net/forums/hero?category=0 由英雄大佬带领的抱团学算法队伍,从0开始,期待你的加入🥳  本博文是对此文章习题所作的题解,如有不足,请多指教:https://blog.csdn.net/WhereIsHeroFrom/article/details/121174370
今日题解: 第一题:https://leetcode-cn.com/problems/max-consecutive-ones/ 
直接遍历,符合相应的条件就让对应的个数相加。
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int number = 0;
int count = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 1){
count++;
number = Math.max(number, count);
}else{
count = 0;
}
}
return number;
}
}
 第二题:https://leetcode-cn.com/problems/maximum-product-of-two-elements-in-an-array/ 
直接用sort函数排序,然后我们把数组里面的每一位的数字先减去一,然后我们一定知道最大值就出现在最后两位。
class Solution {
public int maxProduct(int[] nums) {
Arrays.sort(nums);
int i,max;
for(i=0; i<nums.length; i++){
nums[i] = nums[i] - 1;
}
int len = nums.length;
max = nums[len-1] * nums[len-2];
return max;
}
}

第三题:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/  
一步解决,直接重拳出击!
class Solution {
public int findMin(int[] nums) {
Arrays.sort(nums);
return nums[0];
}
}

或者使用二分法,无非就是用中间的值与两边的关系,因为题里面说了这个数组原来是升序的,所以我们不管怎么转,一定是要考虑中间的那个数字和左右两边的关系,比如中间的数字比右边的数字大,是不是我们的开始那个最小的数字在我们的此时中间值与最右端之间。
class Solution {
public int findMin(int[] nums) {
int low = 0, high = nums.length-1;
while(low < high){
int mid = low + (high - low)/2;
if(nums[mid] <= nums[high]){
high = mid;
}else{
low = mid+1;
}
}
return nums[low];
}
}
 第四题:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/ 
一样的题目,这里直接重拳出击了。
class Solution {
public int findMin(int[] nums) {
Arrays.sort(nums);
return nums[0];
}
}
 第五题:https://leetcode-cn.com/problems/third-maximum-number/ 
对于重复的元素处理没有想到快速的方法,参考了一位大佬的想法,先去重,再排序。针对数组里面的元素个数进行分类讨论。
class Solution {
public int thirdMax(int[] nums) {
Set set= new HashSet();
for (int i:nums) {
set.add(i);
}
Object[] array=set.toArray();
Arrays.sort(array);
int len=array.length;
if(len>=3){
return (int) array[len-3];
}
return (int) array[len-1];
}
}

第六题:https://leetcode-cn.com/problems/maximum-product-of-three-numbers/ 
三个数的最值,那么就要考虑是否含有负数。我们可以先对数组进行升序排序,如果我们的数组开始没有负数,或者只有一个负数,那么我们可以确定,最值出现在最后三位。但是如果有两个负数,或者三个甚至更多,我们可以确定,两个负数才可以诞生一个正数,所以我们只需要判断排序完后的前两位和最后一位的乘积与最后三位的乘积大小。
class Solution {
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
int max = nums[nums.length-1]*nums[nums.length-2]*nums[nums.length-3];
int maxn = nums[0]*nums[1]*nums[nums.length-1];
if(max > maxn){
return max;
}else{
return maxn;
}
}
}

有问题欢迎留言,欢迎加入“万人千题”社区,在这里一起努力。
(今日立冬,今日大雪)

|