[Programmers / JAVA] Level 1 I Don't Like the Same Number (12906)
[Programmers / JAVA] Level 1 I Don't Like the Same Number (12906)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
🔗 I Don't Like the Same Number
You are given an array arr. Each element of the array arr consists of a digit from 0 to 9. You need to remove consecutive duplicate numbers in the array arr, leaving only one of each. However, when returning the remaining numbers after removal, the order of the elements in the array arr must be preserved. For example,
- If arr = [ 1, 1, 3, 3, 0, 1, 1 ], it returns [ 1, 3, 0, 1 ].
- If arr = [ 4, 4, 4, 3, 3 ], it returns [ 4, 3 ].
Complete the solution function that removes consecutive duplicate numbers in the array arr and returns the remaining numbers.
- Size of array arr: a natural number of 1,000,000 or less
- Size of array arr's elements: an integer greater than or equal to 0 and less than or equal to 9
| arr | answer |
|---|---|
| { 1, 1, 3, 3, 0, 1, 1 } | { 1, 3, 0, 1 } |
| { 4, 4, 4, 3, 3 } | { 4, 3 } |
Input/Output Examples #1, 2
Same as the examples in the problem description.
We are given an arbitrary integer array arr. If there are consecutively repeated identical values in this array, we need to remove all of them and keep only one. We need to implement an algorithm that converts consecutive values in this way and returns the result.
Since the problem doesn't ask for the array elements' unique values, we should not use HashSet. For example, looking at Input 1, { 1, 1, 3, 3, 0, 1, 1 } becomes { 1, 3, 0, 1 }, and you can see there are two 1's.
Since we don't know exactly how many elements the result will have, using an ArrayList seems appropriate.
Put arr[0] into the ArrayList as the initial value. Then, starting from arr[1], traverse the array, comparing each element with the last value stored in the ArrayList.
- If the value differs from the last one in the ArrayList, it isn't a duplicate, so add it to the ArrayList.
- If the value is the same as the last one in the ArrayList, it's a duplicate, so skip it.
JAVA
import java.util.ArrayList; /** * I Don't Like the Same Number class * * @author RWB * @since 2021.12.13 Mon 13:32:56 */ class Solution { /** * Method that returns the answer * * @param arr: [int[]] array of digits from 0 to 9 * * @return [int[]] the answer */ public int[] solution(int[] arr) { ArrayList<Integer> list = new ArrayList<>(); list.add(arr[0]); int index = 1; for (int i = 1; i < arr.length; i++) { // If it does not equal the last number in the list if (list.get(index - 1) != arr[i]) { index++; list.add(arr[i]); } } return list.stream().mapToInt(Integer::intValue).toArray(); } }
