[Programmers / JAVA] Level 1 Removing the Smallest Number (12935)
[Programmers / JAVA] Level 1 Removing the Smallest Number (12935)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
🔗 Removing the Smallest Number
Complete the function solution, which returns an array with the smallest number removed from the array of integers arr. However, if the resulting array would be empty, fill the array with -1 and return it. For example, if arr is [4,3,2,1], return [4,3,2], and if it is [10], return [-1].
- arr is an array of length 1 or more.
- For indices i and j, if i ≠ j, then arr[i] ≠ arr[j].
| arr | return |
|---|---|
| { 4, 3, 2, 1 } | { 4, 3, 2 } |
| { 10 } | { -1 } |
Find and remove the smallest number in the array arr, then return the remaining array. If the given array has only one element, that element is the minimum, so excluding it leaves an empty array. In that case, return { -1 }.
Iterate through the array to find the smallest value, remove it, and return the result.
In this section, we use an ArrayList. While iterating through arr, compare for the minimum value and simultaneously add elements to the ArrayList.
Then remove the minimum value from the ArrayList and return it.
JAVA
int min = Integer.MAX_VALUE; for (int item : arr) { min = Math.min(min, item); }
The minimum value is determined as shown above.
JAVA
import java.util.ArrayList; /** * Removing the Smallest Number class * * @author RWB * @since 2021.12.13 Mon 19:20:27 */ class Solution { /** * Method that returns the answer * * @param arr: [int[]] array of integers * * @return [int[]] answer */ public int[] solution(int[] arr) { ArrayList<Integer> list = new ArrayList<>(); int min = Integer.MAX_VALUE; for (int item : arr) { min = Math.min(min, item); list.add(item); } list.remove((Integer) min); // If the list is empty if (list.isEmpty()) { list.add(-1); } return list.stream().mapToInt(Integer::intValue).toArray(); } }
