-
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)); } }
'알고리즘' 카테고리의 다른 글
java로 구현한 dfs와 bfs 코드(백준 1260번, DFS와 BFS) (1) 2023.12.13 재귀 (1) 2023.12.03 딕셔너리 (2) 2023.12.03 LIFO - java (1) 2023.12.02 스택(stack) (1) 2023.12.02