🐍Python/Python_알고리즘

[알고리즘] 52. Minimum Distances

728x90
반응형

We define the distance between two array values as the number of indices between the two values. Given , find the minimum distance between any pair of equal elements in the array. If no such value exists, print .

For example, if , there are two matching pairs of values: . The indices of the 's are  and , so their distance is . The indices of the 's are  and , so their distance is .

Function Description

Complete the minimumDistances function in the editor below. It should return the minimum distance between any two matching elements.

minimumDistances has the following parameter(s):

  • a: an array of integers

Input Format

The first line contains an integer , the size of array .
The second line contains  space-separated integers .

Constraints

Output Format

Print a single integer denoting the minimum  in . If no such value exists, print .

Sample Input

6
7 1 3 4 1 7

Sample Output

3

Explanation
Here, we have two options:

  •  and  are both , so .
  •  and  are both , so .

The answer is .



답 : 



#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the minimumDistances function below.
def minimumDistances(a):
idx = list()
res = list()
for i in range(len(a)):
for j in range(i+1,len(a)):
if a[i] == a[j]:
idx.append([i,j])
for i, (m,n) in enumerate(idx):
res.append(abs(m-n))
if not res:
return -1
else:
return min(res)



if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

n = int(input())

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

result = minimumDistances(a)

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

fptr.close()


같은 숫자가 존재하면 이를 idx list에 추가


그 idx들의 차이에 절대값을 씌우고 최솟값 찾기


값 자체가 없으면 -1 출력 / 있으면 min(res) 값 출력!

728x90
반응형