This time, let’s try Integers.
Just give it a shot and see how it goes…
Question:
Given an array of integers, find the length of the longest subarray with distinct elements.
Solution:
import java.util.Set;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class LongestSubIntegeres {
int x = 0;
public int lengthOfLongestDistinctSubarray(int[] nums) {
int n = nums.length;
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (allUnique(nums,i,j)) ans = Math.max(ans, j - i);
}
}
return ans;
}
public boolean allUnique(int[] n, int start, int end) {
// Set<Character> set = new HashSet<>();
List<Integer> intList = new ArrayList<Integer>(n.length);
for (int i = start; i < end; i++) {
// Character ch = n.charAt(i);
x = n[i];
if (intList.contains(x)) return false;
intList.add(x);
// System.out.println(intList);
}
return true;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 2, 3, 6, 7};
LongestSubIntegeres longestSubarray = new LongestSubIntegeres();
int answer = longestSubarray.lengthOfLongestDistinctSubarray(nums);
System.out.println("The answer is: " + answer);
}
}