zoukankan      html  css  js  c++  java
  • 【leetcode】1509. Minimum Difference Between Largest and Smallest Value in Three Moves

    题目如下:

    Given an array nums, you are allowed to choose one element of nums and change it by any value in one move.

    Return the minimum difference between the largest and smallest value of nums after perfoming at most 3 moves. 

    Example 1:

    Input: nums = [5,3,2,4]
    Output: 0
    Explanation: Change the array [5,3,2,4] to [2,2,2,2].
    The difference between the maximum and minimum is 2-2 = 0.

    Example 2:

    Input: nums = [1,5,0,10,14]
    Output: 1
    Explanation: Change the array [1,5,0,10,14] to [1,1,0,1,1]. 
    The difference between the maximum and minimum is 1-0 = 1.
    

    Example 3:

    Input: nums = [6,6,0,1,1,4,6]
    Output: 2
    

    Example 4:

    Input: nums = [1,5,6,14,15]
    Output: 1

    Constraints:

    • 1 <= nums.length <= 10^5
    • -10^9 <= nums[i] <= 10^9

    解题思路:本题有点意思。要使得最大值和最小值的差最小,那么就要尽量使最小值变大,最大值变小。所以可以分成如下几种情况,一是修改最小的三个值,二是修改最小的两个值以及一个最大值,三是修改最小值以及两个最大值,四是修改最大的三个值,最后比较这四种情况的结果即可。

    代码如下:

    class Solution(object):
        def minDifference(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            nums.sort()
            if len(nums) <= 3:
                return 0
            return min( abs(nums[-1] - nums[3]),abs(nums[-2] - nums[2]),abs(nums[-3] - nums[1]),abs(nums[-4] - nums[0]) )
  • 相关阅读:
    mybatis遍历map
    程序员开发思考-1
    linux shell学习-1
    IDEA tomcat部署
    理解TCP/IP协议
    winform实现自定义折叠面板控件
    目录特殊符号导致的应用程序处于中断模式
    Vue-element-admin实现菜单根据用户权限动态加载
    基于EF的一个简单实战型分层架构
    Linux开启SELinux的情况下怎么解决nginx403跟502错误
  • 原文地址:https://www.cnblogs.com/seyjs/p/13656170.html
Copyright © 2011-2022 走看看