【LEETCODE】52、数组分类,简单级别,题目:717,661,746,628,643,849

package y2019.Algorithm.array;

/**
 * @ProjectName: cutter-point
 * @Package: y2019.Algorithm.array
 * @ClassName: IsOneBitCharacter
 * @Author: xiaof
 * @Description: TODO 717. 1-bit and 2-bit Characters
 * We have two special characters. The first character can be represented by one bit 0.
 * The second character can be represented by two bits (10 or 11).
 * Now given a string represented by several bits.
 * Return whether the last character must be a one-bit character or not. The given string will always end with a zero.
 *
 * Input:
 * bits = [1, 0, 0]
 * Output: True
 * Explanation:
 * The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.
 *
 * 有两种字符,一种是0,一种是10或者11,现在要判断整个数组是否由这两种组成的,要求最后一位的数字必须是单个的0.
 * @Date: 2019/7/10 8:54
 * @Version: 1.0
 */
public class IsOneBitCharacter {

    public boolean solution(int[] bits) {
        //必须最后一个是单个0,中间是10或者11,那么一定是奇数,然后最后一个必须是0
        if(bits[bits.length - 1] != 0) {
            return false;
        }
        //遍历获取结果,每次遍历两个
        for(int i = 0; i < bits.length - 1;) {
            if(bits[i] == 1 && (bits[i + 1] == 0 || bits[i + 1] == 1) && i < bits.length - 2) {
                i += 2;
            } else if (bits[i] == 0) {
                i += 1;
            } else {
                return false;
            }
        }

        return true;
    }

    public static void main(String args[]) {
//        int[] A = {1,0,0};
//        int[] A = {0,0};
        int[] A = {1,1,1,0};
        System.out.println(new IsOneBitCharacter().solution(A));
    }

}
package y2019.Algorithm.array;

/**
 * @ProjectName: cutter-point
 * @Package: y2019.Algorithm.array
 * @ClassName: ImageSmoother
 * @Author: xiaof
 * @Description: TODO 661. Image Smoother
 * Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray
 * scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself.
 * If a cell has less than 8 surrounding cells, then use as many as you can.
 *
 * Input:
 * [[1,1,1],
 *  [1,0,1],
 *  [1,1,1]]
 * Output:
 * [[0, 0, 0],
 *  [0, 0, 0],
 *  [0, 0, 0]]
 * Explanation:
 * For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
 * For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
 * For the point (1,1): floor(8/9) = floor(0.88888889) = 0
 *
 * 包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,
 * 平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们
 *
 * 来源:力扣(LeetCode)
 * 链接:https://leetcode-cn.com/problems/image-smoother
 * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 *
 * @Date: 2019/7/10 9:27
 * @Version: 1.0
 */
public class ImageSmoother {

    public int[][] solution(int[][] M) {
        int[][] result = new int[M.length][M[0].length];
        //直接暴力求解
        for(int i = 0; i < M.length; ++i) {
            for(int j = 0; j < M[i].length; ++j) {
                //8个值得位置
                int minUp = i > 0 ? i - 1 : 0;
                int maxDown = i < M.length - 1 ? i + 1 : M.length - 1;
                int minLeft = j > 0 ? j - 1 : 0;
                int maxRight = j < M[i].length - 1 ? j + 1 : M[i].length - 1;
                int countT = 0, countN = 0;
                //获取所有的数据的平均值
                for(int r = minUp; r <= maxDown; ++r) {
                    for(int c = minLeft; c <= maxRight; ++c) {
                        countN++;
                        countT += M[r][c];
                    }
                }

                result[i][j] = countT / countN;
            }
        }

        return result;
    }

}
package y2019.Algorithm.array;

/**
 * @ProjectName: cutter-point
 * @Package: y2019.Algorithm.array
 * @ClassName: MinCostClimbingStairs
 * @Author: xiaof
 * @Description: TODO 746. Min Cost Climbing Stairs
 * On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
 * Once you pay the cost, you can either climb one or two steps.
 * You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0,
 * or the step with index 1.
 *
 * Input: cost = [10, 15, 20]
 * Output: 15
 * Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
 *
 * 数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。
 * 每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
 * 您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
 *
 * Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
 * Output: 6
 * Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
 * 1(1) + 1(2)
 * 来源:力扣(LeetCode)
 * 链接:https://leetcode-cn.com/problems/min-cost-climbing-stairs
 * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 *
 * @Date: 2019/7/10 9:42
 * @Version: 1.0
 */
public class MinCostClimbingStairs {

    public int solution(int[] cost) {
        //因为每次可以爬一个楼梯,或者2个楼梯,那么dp一维数组
        //爬到n层需要前面MIN{(n-1) + 当前层, 或者n-2 到达当前层,可以最后一层直接跳过
        int[] dp = new int[cost.length + 1];
        int index = 0;
        //可以第一步走一层,或者2层
        dp[0] = cost[0]; dp[1] = cost[1];
        for(int i = 2; i < cost.length + 1; ++i) {
            dp[i] = Math.min(dp[i - 1], dp[i - 2]);
            if(i < cost.length)
                dp[i] += cost[i];
        }

        return Math.min(dp[cost.length - 1], dp[cost.length]);
    }

    public static void main(String args[]) {
//        int[] A = {1,0,0};
//        int[] A = {0,0};
        int[] A = {0,0,0,1};
        System.out.println(new MinCostClimbingStairs().solution(A));
    }

}
package y2019.Algorithm.array;

/**
 * @ClassName MaximumProduct
 * @Description TODO  628. Maximum Product of Three Numbers
 *
 * Given an integer array, find three numbers whose product is maximum and output the maximum product.
 *
 * Input: [1,2,3]
 * Output: 6
 *
 * 给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
 *
 * @Author xiaof
 * @Date 2019/7/10 22:29
 * @Version 1.0
 **/
public class MaximumProduct {

    public int solution(int[] nums) {
        //最大的三个数,除了最大的三个数相乘之外还要考虑一下负数,那么就是2个负数乘以一个正数,那么必须是最小的两个数乘最大的那个数
        Integer[] maxThreeNum = new Integer[3];
        Integer[] minTwoNum = new Integer[2];
        for(int i = 0; i < maxThreeNum.length; ++i) {
            maxThreeNum[i] = null;
        }
        //先值为空,然后遍历
        for(int i = 0; i < nums.length; ++i) {
            //依次和max数组上的数据比较,然后依次吧数组的数据进行调整
            int index = -1; //填入的位置
            for(int j = 0; j < 3; ++j) {
                if(maxThreeNum[j] == null || nums[i] > maxThreeNum[j]) {
                    ++index;
                } else {
                    break;
                }
            }

            if(index > -1) {
                //修改位置
                for(int k = 0; k < index; ++k) {
                    //前面几位从新排序
                    maxThreeNum[k] = maxThreeNum[k+1];
                }
                maxThreeNum[index] = nums[i];
            }

            //计算最小的两个数
            int minIndex = 2;
            for(int j = 1; j >= 0; --j) {
                if(minTwoNum[j] == null || nums[i] < minTwoNum[j]) {
                    --minIndex;
                } else {
                    break;
                }
            }

            if(minIndex < 2) {
                //移动位置
                for(int k = 1; k > minIndex; --k) {
                    minTwoNum[k] = minTwoNum[k - 1];
                }
                minTwoNum[minIndex] = nums[i];
            }
        }

        //最大三个数的乘积
        return Math.max(maxThreeNum[0] * maxThreeNum[1] * maxThreeNum[2], minTwoNum[0] * minTwoNum[1] * maxThreeNum[2]);

    }

    public static void main(String args[]) {
//        int[] A = {1,0,0};
//        int[] A = {0,0};
        int[] A = {-4,-3,-2,-1,60};
        int[] B = {-1,-2,-3};
        System.out.println(new MaximumProduct().solution(B));
    }

}
package y2019.Algorithm.array;

/**
 * @ClassName FindMaxAverage
 * @Description TODO 643. Maximum Average Subarray I
 *
 * Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.
 * Example 1:
 * Input: [1,12,-5,-6,50,3], k = 4
 * Output: 12.75
 * Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
 *
 * Note:
 * 1 <= k <= n <= 30,000.
 * Elements of the given array will be in the range [-10,000, 10,000].
 *
 * 给定 n 个整数,找出平均数最大且长度为 k 的连续子数组,并输出该最大平均数。
 *
 * @Author xiaof
 * @Date 2019/7/10 23:12
 * @Version 1.0
 **/
public class FindMaxAverage {
    public double solution(int[] nums, int k) {
        //每次统计k个数,然后从第k个开始,没多遍历一个数就减去前面一个数
        int sum = 0;
        int result = 0;
        for(int i = 0; i < k; ++i) {
            sum += nums[i];
            result = sum;
        }

        for(int i = k; i < nums.length; ++i) {
            int cur = sum + nums[i] - nums[i - k];
            result = Math.max(cur, result);
            sum = cur;
        }

        return result / (k * 1.0);
    }

    public static void main(String args[]) {
        int[] A = {0,4,0,3,2};
        int[] B = {5};
        int k = 1;
        System.out.println(new FindMaxAverage().solution(B, k));
    }

}
package y2019.Algorithm.array;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MaxDistToClosest
 * @Description TODO 849. Maximize Distance to Closest Person
 *
 * In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.
 * There is at least one empty seat, and at least one person sitting.
 * Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
 * Return that maximum distance to closest person.
 * Example 1:
 * Input: [1,0,0,0,1,0,1]
 * Output: 2
 * Explanation:
 * If Alex sits in the second open seat (seats[2]), then the closest person has distance 2.
 * If Alex sits in any other open seat, the closest person has distance 1.
 * Thus, the maximum distance to the closest person is 2.
 *
 * 在一排座位( seats)中,1 代表有人坐在座位上,0 代表座位上是空的。
 * 至少有一个空座位,且至少有一人坐在座位上。
 * 亚历克斯希望坐在一个能够使他与离他最近的人之间的距离达到最大化的座位上。
 * 返回他到离他最近的人的最大距离。
 * 来源:力扣(LeetCode)
 * 链接:https://leetcode-cn.com/problems/maximize-distance-to-closest-person
 * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 *
 * @Author xiaof
 * @Date 2019/7/10 23:27
 * @Version 1.0
 **/
public class MaxDistToClosest {
    public int solution(int[] seats) {
        //说白了就是求间距最大的中间位置,也就是连续0最长的子串
        int result = 0, n = seats.length, lastNull = -1;
        for(int i = 0; i < seats.length; ++i) {
            if(seats[i] == 1) {
                //遇到人,计算上一个位置到当前位置的空格最大值
                //如果小于0,那就是第一次,也就是可以做开头位置
                result = lastNull < 0 ? i : Math.max((i - lastNull) / 2, result);
                lastNull = i; //遇到人,记录目前最后一次遇到的人的时候
            }
        }

        //判断最后一个位置
        result = Math.max(result, n - lastNull - 1);

        return result;
    }

    public static void main(String args[]) {
        int[] A = {1,0,0,0,1,0,1};
        int[] B = {5};
        int k = 1;
        System.out.println(new MaxDistToClosest().solution(A));
    }
}

原文地址:https://www.cnblogs.com/cutter-point/p/11167442.html

时间: 2024-10-09 05:35:35

【LEETCODE】52、数组分类,简单级别,题目:717,661,746,628,643,849的相关文章

LeetCode OJ平台上Maximum Subarray题目O(n)复杂度解决方案

原始题目如下,意为寻找数组和最大的子串,返回这个最大和即可. Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [?2,1,?3,4,?1,2,1,?5,4], the contiguous subarray [4,?1,2,1] has the largest sum = 6.

LeetCode OJ平台上Maximum Subarray题目O(n)复杂度解决方式

原始题目例如以下,意为寻找数组和最大的子串,返回这个最大和就可以. Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [?2,1,?3,4,?1,2,1,?5,4], the contiguous subarray [4,?1,2,1] has the largest sum =

LeetCode~移除元素(简单)

移除元素(简单) 1. 题目描述 给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度. 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成. 元素的顺序可以改变.你不需要考虑数组中超出新长度后面的元素. 示例 1: 给定 nums = [3,2,2,3], val = 3, 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2. 你不需要考虑数组中超出新长度后面的元素. 示例 2: 给定

LeetCode OJ平台上Sort Colors题目算法探讨

原题如下,意思就是说无序数组(由0,1,2组成),一遍扫描,把数组整理成若干个0-若干个1-若干个2这样的序列. Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integ

leetcode旋转数组查找 二分查找的变形

http://blog.csdn.net/pickless/article/details/9191075 Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return it

滚动数组的简单实用

二维动规是如果只用到本层的和上一层的数据就可以用滚动数组 比如 dp[i,j]=max(dp[i-1,j],dp[i,j-1]); max的意思就不多说了... 具体例子的话,比较经典的就是最长公共子序列,就是 abcde 和 aecd的最长公共子序列就是acd. 如果不是滚动数组的话就是 for i:=1 to length(st1) do for j:=1 to length(st2)do if st1[i]=st2[j] then dp[i,j]:=dp[i-1,j-1]+1 else d

POJ2481 Cows 树状数组的简单应用

题意给了你N头牛,每头牛的强壮值是一个区间[s,e],如果第 i 头牛比第 j 头牛强壮那么必须满足 Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj: 为了满足这三个条件我们进行排序,先以e降序排为先决条件,若e相等则让s升序排列,如此即可满足三个条件,这道题目任意两头牛的强壮值区间有可能完全一样,这样就不需要重新用树状数组求一次和了,直接赋值即可,这样可以省很多时间,因为已经排序处理了,所以即便区间相等的  肯定就是相邻的,所以直接扫一遍即可,若

LeetCode:数组中的第K个最大元素【215】

LeetCode:数组中的第K个最大元素[215] 题目描述 在未排序的数组中找到第 k 个最大的元素.请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素. 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 示例 2: 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 输出: 4 说明: 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度. 题目分析 我们主要来学习一个新的集合类型--优先队列.优先队列作用是保证每次取

foreach ()语法结构提供了遍历数组的简单方式

foreach 语法结构提供了遍历数组的简单方式.foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息.有两种语法: foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement 第一种格式遍历给定的 array_expression 数组.每次循环中,当前单元的值被赋给 $value 并且数组内部的指

数组的简单使用示例

/* ============================================================================ Name : TestArray.c Author : lf Version : Copyright : Your copyright notice Description : 数组的简单使用示例 =======================================================================