출처 : https://leetcode.com/problems/maximum-number-of-pairs-in-array/
You are given a 0-indexed integer array nums
. In one operation, you may do the following:
nums
that are equal.nums
, forming a pair.The operation is done on nums
as many times as possible.
Return a 0-indexed integer array answer
of size 2
where answer[0]
is the number of pairs that are formed and answer[1]
is the number of leftover integers in nums
after doing the operation as many times as possible.
class Solution {
public int[] numberOfPairs(int[] nums) {
int count = 0;
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i : nums) arrayList.add(i);
int j = 0;
int k = j + 1;
boolean flag = true;
while (flag) {
if (arrayList.size() == 1) return new int[]{count, 1};
if (arrayList.size() == 0) return new int[]{count, 0};
if (arrayList.get(j) == arrayList.get(k)) {
count++;
arrayList.remove(j);
arrayList.remove(k - 1);
j = 0; //다시 처음부터 iterate
k = j + 1; //바로 옆 index를 가진 숫자와 비교
} else {
k++; //비교할 대상 바꾸기
}
if (k == arrayList.size()) {
j++; //비교할 대상 내내 찾다가 pair를 못 찾았을 경우
if(j+1 >= arrayList.size()) break;
else k = j + 1;
}
}
return new int[]{count, arrayList.size()};
}
}