zoukankan      html  css  js  c++  java
  • 1338. Reduce Array Size to The Half

    Given an array arr.  You can choose a set of integers and remove all the occurrences of these integers in the array.

    Return the minimum size of the set so that at least half of the integers of the array are removed.

    给一个数组,最少去掉多少个相同的数字,可以使得数组长度小于等于原始长度的一半。

    先统计每个元素出现的次数count,然后再维护一个key是出现次数f,value是出现次数的次数。比如[2,2,3,3,4]->count[0, 2, 2, 1]->f[1, 2, 0, 0]

    然后对于f,index从大到小去遍历,长度减小index步,直到长度小于等于一半。

    class Solution(object):
        def minSetSize(self, arr):
            """
            :type arr: List[int]
            :rtype: int
            """
            count = {}
            for value in arr:
                if value in count:
                    count[value] += 1
                else:
                    count[value] = 1
            f = [0] * (len(arr) + 1)
            for key,value in count.items():
                f[value] += 1
            ans = 0
            step = len(arr)
            k = step // 2
            print(count, f)
            for i in range(len(arr), 0, -1):
                if f[i] != 0:
                    while f[i] > 0:
                        f[i] -= 1
                        step -= i
                        ans += 1
                        if step <= k:
                            return ans
            return ans
                
  • 相关阅读:
    Android实现监测网络状态
    安卓开源库之动画篇
    安卓向服务器发送List数据
    Material Design综合实例
    Material Design入门(三)
    Android之Fragment(二)
    Android之Fragment(一)
    Material Design入门(二)
    Material Design入门
    Android之ActionBar
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13362069.html
Copyright © 2011-2022 走看看