🐍Python/Python_알고리즘

[알고리즘] 47. Equalize the Array

728x90
반응형

Karl has an array of integers. He wants to reduce the array until all remaining elements are equal. Determine the minimum number of elements to delete to reach his goal.

For example, if his array is , we see that he can delete the  elements  and  leaving . He could also delete both twos and either the  or the , but that would take  deletions. The minimum number of deletions is .

Function Description

Complete the equalizeArray function in the editor below. It must return an integer that denotes the minimum number of deletions required.

equalizeArray has the following parameter(s):

  • arr: an array of integers

Input Format

The first line contains an integer , the number of elements in .
The next line contains  space-separated integers .

Constraints

Output Format

Print a single integer that denotes the minimum number of elements Karl must delete for all elements in the array to be equal.

Sample Input

5
3 3 2 1 3

Sample Output

2   

Explanation

Array . If we delete  and , all of the elements in the resulting array, , will be equal. Deleting these  elements is minimal. Our only other options would be to delete  elements to get an array of either  or .


답 : 



#!/bin/python3

import math
import os
import random
import re
import sys
from collections import Counter
# Complete the equalizeArray function below.
def equalizeArray(arr):
res = 0
arr = sorted(arr)
numlist,freqlist = list(),list()
for num,freq in Counter(arr).items():
numlist.append(num)
freqlist.append(freq)
res = len(arr) - max(freqlist)
return res
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

n = int(input())

arr = list(map(int, input().rstrip().split()))

result = equalizeArray(arr)

fptr.write(str(result) + '\n')

fptr.close()



풀다 보니 코드를 더 간결하게 할 수 있을 거 같아서 해보니 한 줄 코드로 가능했다. 



#!/bin/python3

import math
import os
import random
import re
import sys
from collections import Counter
# Complete the equalizeArray function below.
def equalizeArray(arr):
return len(arr) - max(Counter(arr).items(), key = lambda x:x[1])[1]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

n = int(input())

arr = list(map(int, input().rstrip().split()))

result = equalizeArray(arr)

fptr.write(str(result) + '\n')

fptr.close()



배열의 길이 - 가장 높은 freq를 가지는 수의 freq = 답

728x90
반응형