LeetCode第四天
leetcode 第四天
2018年1月4日
15.(628)Maximum Product of Three Numbers
JAVA
class Solution {
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
return (nums[0]*nums[1]*nums[nums.length-1])>(nums[nums.length-1]*nums[nums.length-2]*nums[nums.length-3])?(nums[0]*nums[1]*nums[nums.length-1]):(nums[nums.length-1]*nums[nums.length-2]*nums[nums.length-3]);
}
}
16.(628)Maximum Product of Three Numbers
JAVA
class Solution {
public int thirdMax(int[] nums) {
Integer first = null ,second = null,third = null;
for(Integer n : nums){
if(n.equals(first)||n.equals(second)||n.equals(third)) continue;
if(first==null||n>first){
third = second;
second = first;
first = n;
}else if(second == null||n>second){
third = second;
second = n;
}else if(third == null||n>third){
third = n;
}
}
return third == null?first:third;
}
}
17.(643) Maximum Average Subarray I
JAVA
class Solution {
public double findMaxAverage(int[] nums, int k) {
double window = 0;
double maxAvg = 0;
for(int i =0;i<k;i++){
window +=nums[i];
maxAvg = window;
}
for(int i = k;i<nums.length;i++){
window = window+nums[i]-nums[i-k];
maxAvg = Math.max(maxAvg,window);
}
return maxAvg/k;
}
}
18.(448) Find All Numbers Disappeared in an Array
JAVA
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> result = new ArrayList<Integer>();
for(int i =0;i<nums.length;i++){
nums[Math.abs(nums[i])-1] = -1 * Math.abs(nums[Math.abs(nums[i])-1]);
}
for(int i =0;i<nums.length;i++){
if(nums[i]>0)
result.add(i+1);
}
return result;
}
}
19.(485) Max Consecutive Ones
JAVA
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int max = 0;
int times = 0;
for(int i =0;i<nums.length;i++){
if(nums[i]==1){
times++;
max = Math.max(max,times);
}else{
times = 0;
}
}
return max;
}
}
20.(88) Merge Sorted Array
JAVA
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
while(n > 0){
if(m>0)
nums1[n+m-1] = nums1[m-1]>nums2[n-1]?nums1[--m]:nums2[--n];
else
nums1[n-1] = nums2[--n];
}
}
}
21.(605) Can Place Flowers
JAVA
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0;
for(int i =0;i<flowerbed.length;i++){
if(flowerbed[i]==0&&(i==0||flowerbed[i-1]==0)&&(i==flowerbed.length-1||flowerbed[i+1]==0)){
count++;
flowerbed[i]=1;
if(count==n)
return true;
}
}
return count >= n;
}
}
作者:郭耀华
出处:http://www.guoyaohua.com
微信:guoyaohua167
邮箱:guo.yaohua@foxmail.com
本文版权归作者和博客园所有,欢迎转载,转载请标明出处。
【如果你觉得本文还不错,对你的学习带来了些许帮助,请帮忙点击右下角的推荐】
出处:http://www.guoyaohua.com
微信:guoyaohua167
邮箱:guo.yaohua@foxmail.com
本文版权归作者和博客园所有,欢迎转载,转载请标明出处。
【如果你觉得本文还不错,对你的学习带来了些许帮助,请帮忙点击右下角的推荐】