1. Problems
숫자로 이루어진 정릴되지 않은 2개의 배열을 비교하여 같은 숫자가 몇개인지 찾는다.
- input: source array, target array
- 숫자의 범위는 100 > n >= 0 이고, 중복된 숫자는 들어가지 않는다
- source array에 숫자가 0은 *(와일드카드)로 처리하여 target array에 존재하는 숫자로 변경 하여 카운트 할 수 있다.
2. Solve
두개의 배열을 정렬하고 source array 에서의 0으로 되어 있는 값을 제거하고 그만큼 result count를 증가시킨다.
source array배열에서 모든 배열 원소의 값마다 반복문을 이용하여 target array의 값과 비교한다.
값값이 일치할 경우에 result count를 증가시킨다.
마지막으로 result count를 return 한다.
3. Code
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] sourceArray = {3, 2, 1, 11, 0, 6};
int[] targetArray = {31, 10, 45, 1, 6, 19};
solution(sourceArray, targetArray);
}
public static int solution(int[] sourceArray, int[] targetArray) {
Arrays.sort(sourceArray);
Arrays.sort(targetArray);
int matCount = 0;
int zeroCount = 0;
for(int i = 0; i < sourceArray.length; i++) {
if(sourceArray[i] == 0) {
zeroCount++;
} else {
for(int j = 0; j < targetArray.length; j++) {
if(sourceArray[i] == targetArray[j]) {
matCount++;
break;
}
}
}
}
return matCount + zeroCount;
}
4. Report
Arrays 클래스의 sort를 이용하여 배열을 정렬한 후에 sourceArray의 원소마다 반복문을 실행하여 비교처리했다.
여기서 sourceArray[i] == targetArray[j]의 비교구문 전에 sourceArray[i] > targetArray[j] 일 경우 break 구문을 넣어서 처리해 줄 경우 불필요한 반복을 줄일 수 있을것 같다.
'algorithm' 카테고리의 다른 글
[프로그래머스] 전화번호 목록 (0) | 2021.04.22 |
---|---|
[자유] 10진수 2진수 변환 알고리즘 (0) | 2021.02.28 |
[자유] 이진 탐색 구현 (0) | 2021.02.13 |
[leetCode] 29. Divide Two Integers (0) | 2021.01.23 |
[leetCode] 27. Remove Element (0) | 2021.01.22 |