만족은 하되 안주하지는 말자

기록해야 기억한다

프로그래밍/leetcode

[leetcode] 1007. Minimum Domino Rotations For Equal Row

D36choi 2022. 3. 21. 00:21
728x90

문제

https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/

 

Minimum Domino Rotations For Equal Row - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

내 풀이

import java.util.Arrays;

class Solution {
  public int minDominoRotations(int[] tops, int[] bottoms) {
    int[] rotations = new int[6];
    final int length = tops.length;
    
    for (int i = 1; i <= 6; i++) {
      int topRotationCount = 0;
      int bottomRotationCount = 0;
      
      for (int j = 0; j < length; j++) {
        if(!isPresent(i, tops[j],bottoms[j])) {
          bottomRotationCount = Integer.MAX_VALUE;
          topRotationCount = Integer.MAX_VALUE;
          break;
        }
        if (tops[j] == i && bottoms[j] != i) bottomRotationCount++;
        else if (tops[j] != i && bottoms[j] == i) topRotationCount++;
      }
      
      rotations[i-1] = Math.min(topRotationCount, bottomRotationCount);
    }
    
    Arrays.sort(rotations);
    return rotations[0] == Integer.MAX_VALUE ? -1 : rotations[0];
  }
  private boolean isPresent(int num, int top, int bottom) {
    return top == num || bottom == num;
  }
}

check all number 1 to 6 (N)

  • check all dominos
    • if, top and bottom have no number N, set MAX_INTEGER_VALUE
    • else, find which side is not equal to N
      • and increment counter
  • find min value from top counter and bottom counter

after counting rotation with all number is done, find minimum count

알게 된 것

leetcode.. 문제가 깔끔하고 재밌다. (난이도가 midium이라 그런가)

피드백

어떤 답안은 아래 네가지 케이스를 모두 테스트해 그 중 최소 경우를 찾는 방법도 있었다.

- tops의 모든 수를 tops[0]으로 만드는 경우

- tops의 모든 수를 bottoms[0]으로 만드는 경우

- bottoms의 모든 수를 tops[0]으로 만드는 경우

- bottoms의 모든 수를 bottoms[0]으로 만드는 경우