N개의 최소공배수 -코딩테스트

Jobmania·2022년 12월 5일
0

나의 풀이 방식은 배열을 오름차순으로 정렬한 후
1,2번째 최소공배수를 구한 수를 3번째와 다시 최소공배수를 구하는 것.
Hash Map으로 key값은 더해야되는값 Value는 더한값
ex) key ; 3 / value : 12 으로
각항목의 더한값을 비교하였다. 그리고 구한 최소공배수를 이제 다음 수와 비교해야되기 때문에 배열에 다시 넣어주었다.

코드예시)

public int solution(int[] arr) {
        int answer = 0;
        Arrays.sort(arr);   //배열 오름차순
        int count = 0;

        HashMap<Integer,Integer> map = new HashMap<>();
        int value1=arr[0];
        int value2=arr[1];

        while (true){

            map.put(arr[count], value1);
            map.put(arr[count+1], value2);

            if(map.get(arr[count]).equals(map.get(arr[count+1]))){
                answer = map.get(arr[count]);

            }else if(map.get(arr[count]) > map.get(arr[count+1])){
                value2 = map.get(arr[count+1])+arr[count+1];
                map.put(arr[count],value2);
                continue;
            }else {
                value1 = map.get(arr[count])+arr[count];
                map.put(arr[count],value1);
                continue;
            }

            count++;
            if(count==arr.length-1) break;
            arr[count] = answer;
            value1 = answer;
            value2 = arr[count+1];
        }


        return answer;
    }
profile
HelloWorld에서 RealWorld로

0개의 댓글