공부/알고리즘
Dictionary - 가장 긴 연속된 수열
확두뇌
2023. 12. 3. 19:58
수열 nums의 원소로 만들 수 있는 가장 긴 연속된 수열의 크기를 구하시오.
input: nums = [100, 4, 200, 1, 3, 2], output: 4
input: nums=[0, 3, 7, 2, 5, 8, 4, 6, 0, 1], output: 9
import java.util.HashMap;
public class MostLongSeq {
public static int returnNum(int[] nums) {
HashMap<Integer, String> map = new HashMap<>();
for(int i : nums) {
map.put(i, "");
}
int max = 0;
for(int i=0; i<nums.length; i++) {
int num = 0;
if(!map.containsKey(nums[i]-1) && map.containsKey(nums[i])) {
num++;
int next = nums[i]+1;
while(map.containsKey(next)) {
num++;
next++;
}
}
if(max < num) {
max = num;
}
}
return max;
}
public static void main(String[] args) {
int[] nums = {100,4,200,1,3,2};
int[] nums2 = {0,3,7,2,5,8,4,6,0,1};
System.out.println(returnNum(nums2));
}
}