gpt-3.5-turbo-0125· openai
Suzhen/CodeChat
Do this in Java 11: Write a function: class Solution { public int solution(int[] A); }…
- User
Do this in Java 11:
Write a function:
class Solution { public int solution(int[] A); }
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000].
- Assistantjava
import java.util.HashSet; class Solution { public int solution(int[] A) { HashSet<Integer> set = new HashSet<>(); int max = 0; for (int num : A) { set.add(num); if (num > max) { max = num; } } for (int i = 1; i <= max + 1; i++) { if (!set.contains(i)) { return i; } } return 1; } public static void main(String[] args) { Solution solution = new Solution(); int[] arr1 = {1, 3, 6, 4, 1, 2}; System.out.println(solution.solution(arr1)); // Output: 5 int[] arr2 = {1, 2, 3}; System.out.println(solution.solution(arr2)); // Output: 4 int[] arr3 = {-1, -3}; System.out.println(solution.solution(arr3)); // Output: 1 } }