import java.util.Arrays;

public class Solution {
	
	// 요격 시스템
	
	public static int solution(int[][] targets) {
		int answer = 0;
		
		// 개구간 (s, e)로 표현되는 폭격 미사일을 s와 e에서 발사하는 요격 미사일로는 요격할 수 없기 때문에 각각의 원소에 10을 곱한 후
		// 첫 번째 원소에서는 +1을, 두 번째 원소에서는 -1을 하여 폐구간 [r, f]을 만든 후 [Java] 프로그래머스 [Level-3] 단속카메라 문제처럼 풀도록 한다.
		int[][] tempTargets = new int[targets.length][targets[0].length];
		
		for (int i = 0; i < targets.length; i++) {
			tempTargets[i][0] = targets[i][0] * 10 + 1;
			tempTargets[i][1] = targets[i][1] * 10 - 1;
		}
		
		// int[][] targets = {{4, 5}, {4, 8}, {10, 14}, {11, 13}, {5, 12}, {3, 7}, {1, 4}};
		// int[][] tempTargets = {{41, 49}, {41, 79}, {101, 139}, {111, 129}, {51, 119}, {31, 69}, {11, 39}};
		
		// 이차원 배열 tempTargets 정렬
		Arrays.sort(tempTargets, (o1, o2) -> {
			if (o1[1] == o2[1]) { // 뒤 원소가 같을 경우
				return o1[0] - o2[0]; // 앞 원소 기준 오름차순
			} else { // 뒤 원소가 같지 않을 경우
				return o1[1] - o2[1]; // 뒤 원소 기준 오름차순
			}
		});
		
		// int[][] tempTargets = {{11, 39}, {41, 49}, {31, 69}, {41, 79}, {51, 119}, {111, 129}, {101, 139}};
		
		int missilePoint = tempTargets[0][0] - 1; // 10 // 정렬 후 첫 번째 첫 원소보다 작은 값을 넣기 위해 -1 => 최초 무조건 아래 if문에 걸리게 됨
		
		for (int i = 0; i < tempTargets.length; i++) {
			
			if (missilePoint < tempTargets[i][0]) {
				missilePoint = tempTargets[i][1];
				System.out.println(missilePoint + "번 위치에 미사일 설치");
				answer++;
			}
		}
		
		return answer;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[][] targets = {{4, 5}, {4, 8}, {10, 14}, {11, 13}, {5, 12}, {3, 7}, {1, 4}};
		
		System.out.println(solution(targets)); // 3
	}
}

프로그래머스 요격 시스템 문제 풀이 Java

Annotation이란? 사전적 의미로는 주석이라는 뜻이다.

자바에서 Annotation은 코드 사이에 주석처럼 쓰이며 특별한 의미, 기능을 수행하도록 하는 기술이다.

즉, 프로그램에게 추가적인 정보를 제공해 주는 메타데이터(meta data)라고 볼 수 있다.(meta data : 데이터를 위한 데이터)

다음은 어노테이션의 용도를 나타낸 것이다.

1. 컴파일러에게 코드 작성 문법 에러를 체크하도록 정보를 제공한다.

2. 소프트웨어 개발 툴이 빌드나 배치 시 코드를 자동으로 생성할 수 있도록 정보를 제공한다.

3. 실행 시(런타임 시)특정 기능을 실행하도록 정보를 제공한다.

기본적으로 어노테이션을 사용하는 순서는 다음과 같다.

1. 어노테이션을 정의

2. 클래스에 어노테이션을 배치

3. 코드가 실행되는 중 Reflection(프로그램이 실행 중에 자신의 구조와 동작을 검사하고, 조사하고, 수정하는 것)을 이용하여 추가 정보를 획득하여 기능을 실시

 

Annotation 종류

 

@ComponentScan

@Component, @Service, @Repository, @Controller, @Configuration이 붙은 클래스 Bean들을 찾아서 Context에 bean등록을 해주는 Annotation

 

@Component

개발자가 직접 작성한 Class를 Bean으로 등록하기 위한 Annotation

 

@Bean

개발자가 직접 제어가 불가능한 외부 라이브러리등을 Bean으로 만들려할 때 사용되는 Annotation

 

@Autowired

field, setter method, constructor에서 사용하며 Type에 따라 알아서 Bean을 주입 해준다.

Controller 클래스에서 DAO나 Service에 관한 객체들을 주입 시킬 때 많이 사용

 

Bean을 주입받는 3가지 방식

1. @Autowired

2. setter

3. 생성자(@AllArgsConstructor 사용) -> 권장방식

 

@Inject

@Autowired 어노테이션과 비슷한 역할

 

@Controller

Spring의 Controller를 의미하며, Spring MVC에서 Controller 클래스에 쓰인다.

 

@RestController

Spring에서 Controller 중 View로 응답하지 않는, Controller를 의미

method의 반환 결과를 JSON 형태로 반환

 

@Controller 와 @RestController 차이

@Controller
API와 view를 동시에 사용하는 경우에 사용
대신 API 서비스로 사용하는 경우는 @ResponseBody를 사용하여 객체를 반환
view(화면) return이 주목적

@RestController
view가 필요없는 API만 지원하는 서비스에서 사용
Spring 4.0.1부터 제공
@RequestMapping 메서드가 기본적으로 @ResponseBody 의미를 가정
data(json, xml 등) return이 주목적

즉, @RestController = @Controller + @ResponseBody

 

@Service

Service Class에서 쓰인다. 비즈니스 로직을 수행하는 Class라는 것을 나타내는 용도

 

@Repository

DAO Class(DataBase에 접근하는 method를 가지고 있는 Class)에서 쓰인다.

 

@EnableAutoConfiguration

Spring Application Context를 만들 때 자동으로 설정하는 기능을 켠다.

(classpath의 내용에 기반해서 자동으로 생성, 만약 tomcat-embed-core.jar가 존재하면 톰캣 서버가 setting)

 

@Configuration

@Configuration을 클래스에 적용하고 @Bean을 해당 Class의 method에 적용하면 @Autowired로 Bean을 부를 수 있다.

 

@Required

setter method에 적용해주면 Bean 생성시 필수 프로퍼티 임을 알린다.

 

@Qualifier("id")

@Autowired와 같이 쓰이며, 같은 타입의 Bean 객체가 있을 때 해당 아이디를 적어 원하는 Bean이 주입될 수 있도록 한다.

 

@Resource

@Autowired와 마찬가지로 Bean 객체를 주입해주는데 차이점이 있다.

Autowired는 타입으로, Resource는 이름으로 연결한다.

 

@PostConstruct, @PreConstruct

의존하는 객체를 생성한 이후 초기화 작업을 위해 객체 생성 전/후에 실행해야 할 method 앞에 붙인다.

 

@PreDestroy

객체를 제거하기 전에 해야할 작업을 수행하기 위해 사용

 

@PropertySource

해당 프로퍼티 파일을 Environment로 로딩하게 해준다.

 

@ConfigurationProperties

yaml파일 읽는다. default로 classpath:application.properties 파일이 조회

 

@Lazy

지연로딩을 지원

@Component나 @Bean Annotation과 같이 쓰는데 Class가 로드될 때 스프링에서 바로 bean등록을 마치는 것이 아니라 실제로 사용될 때 로딩이 이뤄지게 하는 방법

 

@Value

properties에서 값을 가져와 적용할 때 사용

 

@SpringBootApplication

@Configuration, @EnableAutoConfiguration, @ComponentScan 3가지를 하나의 어노테이션으로 합친 것

 

@RequestMapping

요청 URL을 어떤 method가 처리할지 mapping해주는 Annotation

 

@CookieValue

쿠키 값을 parameter로 전달 받을 수 있는 방법

 

@CrossOrigin

CORS 보안상의 문제로 브라우저에서 리소스를 현재 origin에서 다른 곳으로의 AJAX요청을 방지하는 것

 

@ModelAttribute

view에서 전달해주는 parameter를 Class(VO/DTO)의 멤버 변수로 binding 해주는 Annotation

 

@GetMapping

@RequestMapping(Method=RequestMethod.GET)과 같다.

 

@SessionAttributes

Session에 data를 넣을 때 쓰는 Annotation

 

@Valid

유효성 검증이 필요한 객체임을 지정

 

@InitBinder

@Valid 어노테이션으로 유효성 검증이 필요하다고 한 객체를 가져오기전에 수행해야할 method를 지정

 

@RequestAttribute

Request에 설정되어 있는 속성 값을 가져올 수 있다.

 

@RequestBody

요청이 온 데이터(JSON이나 XML형식)를 바로 Class나 model로 매핑하기 위한 Annotation

 

@RequestHeader

Request의 header값을 가져올 수 있다. 메소드의 파라미터에 사용

 

@RequestParam

@PathVariable과 비슷, request의 parameter에서 가져오는 것

 

@RequestPart

Request로 온 MultipartFile을 바인딩

 

@ResponseBody

HttpMessageConverter를 이용하여 JSON 혹은 xml로 요청에 응답할 수 있게 해주는 Annotation

 

@PathVariable

method parameter 앞에 사용하면서 해당 URL에서 {특정값}을 변수로 받아 올 수 있다.

 

@ExceptionHandler

해당 클래스의 예외(Exception)를 캐치하여 처리

 

@ControllerAdvice

Class 위에 ControllerAdvice를 붙이고 어떤 예외를 잡아낼 것인지는 각 메소드 상단에

@ExceptionHandler(예외클래스명.class)를 붙여서 기술

 

@RestControllerAdvice

@ControllerAdvice + @ResponseBody

 

@ResponseStatus

사용자에게 원하는 response code와 reason을 return해주는 Annotation

 

@EnableEurekaServer

Eureka 서버로 만들어준다.

 

@EnableDiscoveryClient

Eureka 서버에서 관리될 수 있는 클라이언트 임을 알려주기위한 Annotation

 

@Transactional

데이터베이스 트랜잭션을 설정하고 싶은 method에 이 Annotation을 적용하면 method 내부에서 일어나는 데이터베이스 로직이 전부 성공하거나, 데이터베이스 접근중 하나라도 실패하면 다시 롤백할 수 있게 해주는 Annotation

 

@Cacheable

method 앞에 지정하면 해당 method를 최초에 호출하면 캐시에 적재하고 다음부터는 동일한 method 호출이 있을 때 캐시에서 결과를 가져와서 return하므로 method 호출 횟수를 줄여주는 Annotation

 

@CachePut

캐시를 업데이트하기 위해서 method를 항상 실행하게 강제하는 Annotation

 

@CacheEvict

캐시에서 데이터를 제거하는 트리거(Trigger)로 동작하는 method에 붙이는 Annotation

 

@CacheConfig

클래스 레벨에서 공통의 캐시설정을 공유하는 기능

 

@Scheduled

Linux의 crontab처럼 정해진 시간에 실행해야하는 경우에 사용

 

Lombok Annotation 종류

 

@NoArgsConstructor

기본 생성자를 자동으로 추가

 

@AllArgsConstructor

모든 필드 값을 파라미터로 받는 생성자를 추가

 

@RequiredArgsConstructor

final(값이 할당되면 더 이상 변경할 수 없음) 이나 @NonNull인 필드 값만 파라미터로 받는 생성자를 추가

 

@Getter

Class 내 모든 필드의 Getter method를 자동 생성

 

@Setter

Class 내 모든 필드의 Setter method를 자동 생성

 

@ToString

Class 내 모든 필드의 toString method를 자동 생성

 

@EqualsAndHashCode

equals와 hashCode method를 오버라이딩 해주는 Annotation

 

@Builder

어느 필드에 어떤 값을 채워야 할지 명확하게 정하여 생성 시점에 값을 채워준다.

 

Constructor 와 @Builder 차이

생성 시점에 값을 채워주는 역할은 똑같다. 하지만 Builder를 사용하면 어느 필드에 어떤 값을 채워야 할지 명확하게

인지할 수 있다. 해당 Class의 Builder 패턴 Class를 생성 후 생성자 상단에 선언 시 생성자에 포함된 필드만 빌더에 포함

 

@Data

@Getter, @Setter, @EqualsAndHashCode, @AllArgsConstructor을 포함한 Lombok에서 제공하는 필드와 관련된

모든 코드를 생성

 

JPA Annotation 종류

 

@Entity

실제 DB의 테이블과 매칭될 Class임을 명시

즉, 테이블과 링크될 클래스임을 나타냄

 

@Table

Entity Class에 매핑할 테이블 정보를 알려줌

 

@Id

해당 테이블의 PK 필드를 나타냄

 

@GeneratedValue

PK의 생성 규칙을 나타냄

 

@Column

테이블의 컬럼을 나타내며, 굳이 선언하지 않더라도 해당 Class의 필드는 모두 컬럼이 됨

'Java > 참고자료' 카테고리의 다른 글

[Java] Equals & HashCode  (0) 2022.11.25
[Java] Exception  (0) 2022.11.25
[Java] Comparable & Comparator  (0) 2022.11.25
[Java] 연산자  (0) 2022.11.25
[Java] Stack, Queue, Deque  (0) 2022.11.25
public class Solution {
	
	// 네트워크
	
	static boolean[] visited = {};
	
	public static void dfs(int i, int[][] computers) {
		visited[i] = true;
		
		for(int j = 0; j < computers[i].length; j++) {
			
			if(!visited[j] && computers[i][j] == 1) {
				dfs(j, computers);
			}
		}
	}
	
	public static int solution(int n, int[][] computers) {
		int answer = 0;
		
		visited = new boolean[n];
		
		for(int i = 0; i < n; i++) {
        	
			if(!visited[i]) {
				answer++;
				dfs(i, computers);
			}
		}
        
		return answer;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int n = 3; // 3대의 컴퓨터
		int[][] computers = {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}}; // 연결된 네트워크
		
		System.out.println(solution(n, computers)); // 2
	}
}

프로그래머스 네트워크 문제 풀이 Java

public class Solution {
	
	// 단어 변환
	
	static boolean[] visited = {};
	static int gDepth = 0;
	
	public static boolean strCompare(String str1, String str2) { // str1과 str2의 길이가 같다는 조건 하에
		int strLength = str1.length();
		int cnt = 0;
		
		for(int i = 0; i < strLength; i++) {
			
			if(str1.charAt(i) != str2.charAt(i)) {
				cnt++;
			}
		}
		
		if(cnt == 1) { // 변형 조건에서 1글자만 바꿀 수 있는데 1글자만 다를 경우
			return true;
		} else {
			return false;
		}
	}
	
	public static int dfs(String begin, String target, String[] words, int depth) { // hit // cog // {"hot", "dot", "dog", "lot", "log", "cog"}
		
		int mDepth = 0;
		
		for(int i = 0; i < words.length; i++) {
			
			mDepth = depth;
			
			if(visited[i]) {
				continue;
			}
			
			if(strCompare(begin, words[i])) { // 1글자만 다른 경우, 즉 변경 가능한 경우
				begin = words[i]; // 바꿀 단어를 비교 대상으로 변경
				mDepth++;
				visited[i] = true; // 사용한 단어 방문 처리
				
				dfs(begin, target, words, mDepth);
				
				if(begin.equals(target)) {
					System.out.println(mDepth + "번 변경으로 가능");
					gDepth = mDepth;
					break;
				}
			} else {
				continue;
			}
		}
		return gDepth;
	}
	
	public static int solution(String begin, String target, String[] words) {
		int answer = 0;
		
		visited = new boolean[words.length];
		
		answer = dfs(begin, target, words, 0);
		
		return answer;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String begin = "hit";
		String target = "cog";
		String[] words = {"hot", "dot", "dog", "lot", "log", "cog"}; // hot -> dot -> dog -> cog
		
		System.out.println(solution(begin, target, words)); // 4
	}
}

프로그래머스 단어 변환 문제 풀이 Java

import java.util.PriorityQueue;

public class Solution {
	
	// 디펜스 게임
	
	public static int solution(int n, int k, int[] enemy) {
		int answer = enemy.length; // 모든 라운드 클리어 가능할 경우의 리턴 값
		
		PriorityQueue<Integer> pq = new PriorityQueue<>(); // 무적권을 사용해 해치울 적의 수를 남기기 위한 우선순위 큐
		
		// 디펜스 게임 시작
		for(int i = 0; i < enemy.length; i++) { // 4, 2, 4, 5, 3, 3, 1
			pq.offer(enemy[i]); // 4 // 2, 4 // 2, 4, 4 // 2, 4, 4, 5 // 3, 4, 4, 5 // 3, 4, 4, 5
			
			// 무적권은 3개이므로 pq에 4개 이상 라운드가 담기면 그중 가장 적은 적이 나타나는 라운드는 병사를 소모하여 클리어
			if(pq.size() > k) { // false // false // false // true // true // true
				n -= pq.poll(); // 7 // 7 // 7 // 5 // 2 // -1
			}
			
			if(n < 0) { // false // false // false // false // false // true
				return i; // enemy 배열의 6번째 숫자에서 음수가 나오므로 enemy 배열의 5번째 숫자까지는 pass // 5라운드까지 진출 가능
			}
		}
		
		return answer; // 여기까지 내려왔다는 것은 모든 적을 해치우고도 병사가 남았다는 얘기 즉, 모든 라운드 클리어 가능
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int n = 7; // 병사 수
		int k = 3; // 무적권 수
		int[] enemy = {4, 2, 4, 5, 3, 3, 1}; // 라운드별 적 수
		
		System.out.println(solution(n, k, enemy)); // 5
	}
}

프로그래머스 디펜스 게임 문제 풀이 Java

public class Solution {

	// 이동하기 - DP 11048번
	
	static int n = 3;
	static int m = 4;
	static int[][] arr = {{1, 2, 3, 4}, {0, 0, 0, 5}, {9, 8, 7, 6}};
	static int[] dy = {1, 1, 0};
	static int[] dx = {0, 1, 1};
	static int[][] dp = new int[n][m];
	
	public static void dfs(int a, int b) {
		
		for(int i = 0; i < 3; i++) {
			int ny = a + dy[i];
			int nx = b + dx[i];
			
			if(ny > n - 1 || nx > m - 1) {
				continue;
			}
			
			// dp 갱신 후 dfs(순서 잘 생각)
			dp[ny][nx] = Math.max(dp[ny][nx], arr[ny][nx] + dp[a][b]);
			dfs(ny, nx);
		}
	}
	
	public static void dynamicProgramming() {
		dp[0][0] = arr[0][0];
		dfs(0,0);
		
		for(int i = 0; i < n; i++) {
			
			for(int j = 0; j < m; j++) {
				System.out.print(dp[i][j] + " ");
			}
            
			System.out.println();
		}
		
		System.out.println("얻을 수 있는 최대 사탕 개수 : " + dp[n - 1][m - 1]);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// (1,1) 좌상단에서 (N,M) 우하단까지 사탕 최대로 얻기
		dynamicProgramming();
	}
}

백준 DP 11048번 이동하기

'Java > 백준' 카테고리의 다른 글

[Java] 백준 [2178] 미로 탐색  (0) 2022.12.24
[Java] 백준 [1541] 잃어버린 괄호  (0) 2022.12.18
[Java] 백준 [7570] 줄 세우기  (0) 2022.12.17
[Java] 백준 [2631] 줄 세우기  (0) 2022.12.17
[Java] 백준 [9095] 1, 2, 3 더하기  (0) 2022.12.16
import java.util.LinkedList;
import java.util.Queue;

public class Solution {

	// 미로 탐색 - BFS 2178번
	// 최단 거리 탐색 BFS
	
	static int r = 4;
	static int c = 6;
	static int[][] arr = {{1, 0, 1, 1, 1, 1}, {1, 0, 1, 0, 1, 0}, {1, 0, 1, 0, 1, 1}, {1, 1, 1, 0, 1, 1}};
	static boolean[][] visit = {};
	static int[] dx = {0, 0, -1, 1};
	static int[] dy = {-1, 1, 0, 0};
	
	public static void bfs(int n, int m) {
		
		Queue<int[]> q = new LinkedList<>();
		
		q.offer(new int[] {n,m});
		
		visit[n][m] = true;
		
		while(!q.isEmpty()) {
			
			int[] tempArr = q.poll();
			int row = tempArr[0];
			int col = tempArr[1];
			
			for(int i = 0; i < 4; i++) {
				int nextX = col + dx[i];
				int nextY = row + dy[i];
				
				if(nextX < 0 || nextY < 0 || nextX >= c || nextY >= r) {
					continue;
				}
				
				if(visit[nextY][nextX] || arr[nextY][nextX] == 0) {
					continue;
				}
				
				q.offer(new int[] {nextY,nextX});
				arr[nextY][nextX] = arr[row][col] + 1;
				visit[nextY][nextX] = true;
			}
		}
		
		System.out.println(arr[r-1][c-1]);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		visit = new boolean[r][c];
		
		bfs(0, 0);
	}
}

백준 BFS 2178번 미로 탐색

'Java > 백준' 카테고리의 다른 글

[Java] 백준 [11048] 이동하기  (0) 2022.12.26
[Java] 백준 [1541] 잃어버린 괄호  (0) 2022.12.18
[Java] 백준 [7570] 줄 세우기  (0) 2022.12.17
[Java] 백준 [2631] 줄 세우기  (0) 2022.12.17
[Java] 백준 [9095] 1, 2, 3 더하기  (0) 2022.12.16
public class Solution {
	
	// 잃어버린 괄호 - Greedy 1541번
	
	public static int solution(String str) {
		String[] strArr1 = str.split("-"); // 문자 "-" 기준으로 split
		int totalSum = 0;
		int tempSum = 0;
		
		// strArr1 = {"55", "50+40", "20", "30+40"}
		
		for (int i = 0; i < strArr1.length; i++) {
			
			tempSum = 0;
			
			String[] strArr2 = strArr1[i].split("\\+"); // 특수문자 "+" 기준으로 split (특수문자의 경우 \\특수문자 or [특수문자])
			
			for (int j = 0; j < strArr2.length; j++) {
				tempSum += Integer.parseInt(strArr2[j]);
			}
			
			if (i == 0) { // 처음 구간은 +
				totalSum += tempSum; // +55
			} else { // 이후 구간은 -
				totalSum -= tempSum; // -90-20-70
			}
		}
		
		return totalSum;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str = "55-50+40-20-30+40"; // (55)-(50+40)-(20)-(30+40) 이 값이 최소가 된다.
		
		System.out.println(solution(str)); // -125
	}
}

백준 Greedy 1541번 잃어버린 괄호

'Java > 백준' 카테고리의 다른 글

[Java] 백준 [11048] 이동하기  (0) 2022.12.26
[Java] 백준 [2178] 미로 탐색  (0) 2022.12.24
[Java] 백준 [7570] 줄 세우기  (0) 2022.12.17
[Java] 백준 [2631] 줄 세우기  (0) 2022.12.17
[Java] 백준 [9095] 1, 2, 3 더하기  (0) 2022.12.16

+ Recent posts