매일 Algorithm

신재원·2023년 5월 25일
1

Algorithm

목록 보기
130/243

프로그래머스 (평행)

public class problem435 {
    class Solution {
        // 기울기가 같아야 평행 함
        // 기울기 공식 (y2 - y1) / (x2 - x1)
        public double find(int[] dot1, int[] dot2) {
            return (double) (dot2[1] - dot1[1]) / (dot2[0] - dot1[0]);
        }

        public int solution(int[][] dots) {
            int answer = 0;
            // dots 2차원 배열 dots[0] = dots[0][*] 이다.
            // (0,1) (2,3)
            if (find(dots[0], dots[1]) == find(dots[2], dots[3])) {
                answer = 1;
            }
            // (0,2) (1,3)
            if (find(dots[0], dots[2]) == find(dots[1], dots[3])) {
                answer = 1;
            }
            // (0,3) (1,2)
            if (find(dots[0], dots[3]) == find(dots[1], dots[2])) {
                answer = 1;
            }

            return answer;
        }
    }
}

프로그래머스 (기사단의 무기)

public class problem436 {
    class Solution {

        public int solution(int number, int limit, int power) {
            int[] arr = new int[number + 1];

            // 약수갯수 구하기
            // number = 5 일때 1,2,3,4,5 인덱스가 다 증가합니다.
            // i의 배수들의 인덱스를 증가시킴
            for(int i = 1; i <= number; i++){
                for(int j = i; j <= number; j+=i){
                    arr[j]++;
                }
            }
            int answer = 0;

            // 철의 무게 총합 구하기
            for(int i = 1; i <= number; i++){
                if(arr[i] > limit){
                    answer += power;
                }else{
                    answer += arr[i];
                }
            }

            return answer;
        }
    }
}

프로그래머스 (영어 끝말잇기)

import java.util.HashMap;
import java.util.Map;
public class problem437 {
    class Solution {
        public int[] solution(int n, String[] words) {
            int[] answer = {0, 0};

            Map<String, Integer> map = new HashMap<>();
            for (int i = 0; i < words.length; i++) {

                if (i != 0) {
                    String str1 = words[i - 1];
                    String str2 = words[i];
                    
                    // 문자열의 끝 문자
                    char last = str1.charAt(str1.length() - 1);

                    // 문자열의 첫 문자
                    char first = str2.charAt(0); 
                    
                    // containsKey() : 해당 key값이 있으면 true / false로 반환
                    if (map.containsKey(str2) || first != last) {
                        answer[0] = (i % n) + 1; // 순서

                        // + 1 해주는 이유는 words.length 까지임으로
                        answer[1] = (i / n) + 1; // 차례
                        return answer;
                    }

                }
                map.put(words[i], 1); // map 객체에 문자열 저장
            }
            return answer;
        }
    }
}

0개의 댓글