zoukankan      html  css  js  c++  java
  • 【leetcode】1664. Ways to Make a Fair Array

    题目如下:

    You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.

    For example, if nums = [6,1,7,4,1]:

    • Choosing to remove index 1 results in nums = [6,7,4,1].
    • Choosing to remove index 2 results in nums = [6,1,4,1].
    • Choosing to remove index 4 results in nums = [6,1,7,4].

    An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.

    Return the number of indices that you could choose such that after the removal, nums is fair.

    Example 1:

    Input: nums = [2,1,6,4]
    Output: 1
    Explanation:
    Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.
    Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.
    Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.
    Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.
    There is 1 index that you can remove to make nums fair.
    

    Example 2:

    Input: nums = [1,1,1]
    Output: 3
    Explanation: You can remove any index and the remaining array is fair.
    

    Example 3:

    Input: nums = [1,2,3]
    Output: 0
    Explanation: You cannot make a fair array after removing any index.

    Constraints:

    • 1 <= nums.length <= 105
    • 1 <= nums[i] <= 104

    解题思路:题目本身不难,而且nums.length 最大只有105,可以随便折腾。

    代码如下:

    class Solution(object):
        def waysToMakeFair(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            res = 0
            even = []
            odd = []
            even_amount = odd_amount = 0
            for i in range(len(nums)):
                if i % 2 == 0:
                    even_amount += nums[i]
                else:
                    odd_amount += nums[i]
                even.append(even_amount)
                odd.append(odd_amount)
    
            even_amount = odd_amount = 0
            for i in range(len(nums)):
                if even_amount + (odd[-1] - odd[i]) == odd_amount + (even[-1] - even[i]):
                    res += 1
                if i % 2 == 0:
                    even_amount += nums[i]
                else:
                    odd_amount += nums[i]
    
            #print even
            #print odd
    
            return res
  • 相关阅读:
    【转】深入理解CSS定位中的偏移
    【转】css清除浮动float的三种方法总结,为什么清浮动?浮动会有那些影响?
    执行sql时出现错误 extraneous input ';' expecting EOF near '<EOF>'
    jquery操作select(增加,删除,清空)
    mybatis 错误CGLIB is not available
    spring事务不会进行回滚的情况
    Hive 存储类型 StoreType
    Sublimetext3安装Emmet插件步骤
    spring-mvc List及数组的配置接收
    solr 学习片段
  • 原文地址:https://www.cnblogs.com/seyjs/p/14931556.html
Copyright © 2011-2022 走看看