728x90

유저 아이디 배열과 "신고자 피신고자" 배열, 제재 대상 기준 횟수가 주어질때 ,

신고자가 신고한 유저가 제재 대상이 되면 신고자에게 메일을 보내고

이때 신고자가 받은 메일의 개수를 담은 배열을 반환  

public int[] solution(String[] id_list, String[] report, int k) {

int[] answer = new int[id_list.length];

Map<String,Set<String>> reportedMap = new HashMap<String,Set<String>>();//K:신고당한사람 V:신고한사람SET

ArrayList<String> id = new ArrayList<String>();//answer에 저장할때 index를 알아내기 위해 id_list와 같은 순서로 add

for (int i = 0; i < id_list.length; i++) {

id.add(id_list[i]);

}

for(int i=0; i<report.length;i++){

Set<String> thoseReporting = reportedMap.getOrDefault(report[i].split(" ")[1],new HashSet<String>());//신고한사람SET

thoseReporting.add(report[i].split(" ")[0]);

reportedMap.put(report[i].split(" ")[1],thoseReporting);

}

Set<String> reportedSet = reportedMap.keySet();

for (Iterator iterator = reportedSet.iterator(); iterator.hasNext();) {

String string = (String) iterator.next();

Set<String> a = reportedMap.get(string);

if(a.size()>=k) {

for (Iterator iterator2 = a.iterator(); iterator2.hasNext();) {

String string2 = (String) iterator2.next();

answer[id.indexOf(string2)]++;

}

}

}

return answer;

}

 

다른사람 풀이를 보는데   객체 지향으로 푼 사람이 있었다. 

class User{

String name;

HashSet<String> reportList;

HashSet<String> reportedList;

public User(String name){

this.name = name;

reportList = new HashSet<>();

reportedList = new HashSet<>();

}

}

유저 객체는

본인 이름과 

본인이 신고한 사람 set, 본인을 신고한 사람 set을 가지고 있다.   

public int[] solution2(String[] id_list, String[] report, int k) {

int[] answer = new int[id_list.length];

ArrayList<User> users = new ArrayList<>();

HashMap<String, Integer> suspendedList = new HashMap<>(); // <이름>

HashMap<String, Integer> idIdx = new HashMap<String, Integer>(); // <이름, 해당 이름의 User 클래스 idx>

int idx = 0;

 

for (String name : id_list) {

idIdx.put(name, idx++);

users.add(new User(name));

}

 

for (String re : report) {

String[] str = re.split(" ");

users.get(idIdx.get(str[0])).reportList.add(str[1]);//신고가 한번 발생하면 신고 당한사람과 신고한 사람의리스트 모두 갱신 

users.get(idIdx.get(str[1])).reportedList.add(str[0]);

}

 

for (User user : users) {

if (user.reportedList.size() >= k)//신고당한 횟수가 k번 이상이면

suspendedList.put(user.name, 1);//제재리스트에 유저이름을 올린다.

}

 

for (User user : users) {

for (String nameReport : user.reportList) {

if (suspendedList.get(nameReport) != null) {//제재 대상에 이름이있다면 

answer[idIdx.get(user.name)]++;//그 이름으로 index 찾아서 answer증가

}

 

}

}

return answer;

 

}

'Java > Coding Test' 카테고리의 다른 글

달리기 경주 문제풀이  (0) 2023.09.24
공원 산책 문제풀이  (0) 2023.09.24
소수찾기 문제풀이  (0) 2023.09.18
소인수분해 문제풀이  (0) 2023.09.18
치킨 쿠폰 문제풀이  (0) 2023.09.17
728x90

RestApi method

 

GET 서버의 리소스에 접근
POST 서버에 데이터 전송
PUT 서버의 리소스를 갱신
DELETE 서버의 리소스 삭제

 

URI 맵핑 

site/items/sub-items/pk

 기존에 uri를 설계할 때는 'site/items_service' 처럼 자원과 그 행위를 표현하는 방식을 많이 사용했는데 

RestApi는 행위는 RequestMethod로 충분하고

- URI는 자원을 표현한다. 

- /은 자원의 계층관계를 나타내고 URI 마지막에 붙이지 않는다. 

- _은 사용하지 않는다. -은 가독성을 위해 사용할 수 있다.

-  소문자를 사용한다. 

- 파일 확장자.xx는 사용하지 않는다. 

- 컬렉션(집합)자원은 s(복수형)을 붙이고, 다큐먼트(객체) 자원은 단수형을 사용하면 직관적인 설계가 될 수 있다.

 

 

HTTP 응답상태 코드 

- 2xx : 정상적 응답

- 301 : redirect 된 경우 

- 4xx : 클라이언트의 부적절한 요청에 대한 응답 

- 500 : 서버측에 문제 발생

 

RestController

@GetMapping(value = "/guests",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

public Map<String,Object> guest_list()throws Exception{

Map<String, Object> resultMap=new HashMap<String, Object>();

int status=1;

String msg="성공";

List<Guest> data=new ArrayList<Guest>();

data=guestService.selectAll();

resultMap.put("status", status);

resultMap.put("msg", msg);

resultMap.put("data", data);

 

return resultMap;

}

@GetMapping(value = "/guests/{guest_no}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

public Map<String,Object> guest_detail(@PathVariable(value = "guest_no") int guest_no )throws Exception{

Map<String, Object> resultMap=new HashMap<String, Object>();

int status=1;

String msg="성공";

List<Guest> data=new ArrayList<Guest>();

Guest guest=guestService.selectByNo(guest_no);

if(guest!=null) {

data.add(guest);

}else {

status=2;

msg="게시물이 존재하지않습니다.";

}

 

resultMap.put("status", status);

resultMap.put("msg", msg);

resultMap.put("data", data);

 

return resultMap;

}

guests URI 에 파라메터를 받아서 queryString으로 맵핑하지 않고 

guests/{guest_no}로 guest_no를 URI PathVariable로 받아서 맵핑한다. 

@PostMapping(value = "/guests",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

public Map<String,Object> guest_write_action(@RequestBody Guest guest){

Map<String, Object> resultMap=new HashMap<String, Object>();

int status=1;

String msg="성공";

List<Guest> data=new ArrayList<Guest>();

try {

int insert_guest_no=guestService.insertGuest(guest);

status=1;

msg="성공";

Guest newGuest=guestService.selectByNo(insert_guest_no);

data.add(newGuest);

} catch (Exception e) {

status=2;

msg="방명록쓰기실패";

e.printStackTrace();

}

 

resultMap.put("status", status);

resultMap.put("msg", msg);

resultMap.put("data", data);

return resultMap;

}

동일한 guests URI에 POST 방식으로 요청을 보내는 컨트롤러 

Model이나 Request Param이 아닌 

RequestBody 어노테이션을 사용

@Operation(summary = "방명록수정",description = "전송되는아이디에해당하는 게시물수정")

@Parameter(name = "guest_no",description = "방명록의번호")

@PutMapping(value = "/guests/{guest_no}")

public Map<String,Object> guest_modify_action( @PathVariable("guest_no") int guest_no,

@RequestBody Guest guest)throws Exception{

Map<String, Object> resultMap=new HashMap<String, Object>();

int status=1;

String msg="성공";

List<Guest> data=new ArrayList<Guest>();

guest.setGuest_no(guest_no);

guestService.updateGuest(guest);

data.add(guest);

 

resultMap.put("status", status);

resultMap.put("msg", msg);

resultMap.put("data", data);

 

return resultMap;

}

Put 방식으로 맵핑

//@ExceptionHandler(Exception.class)

public Map<String,Object> exceptionHandler(Exception e){

Map<String, Object> resultMap=new HashMap<String, Object>();

int status=3;

String msg="알수없는예외";

List data=new ArrayList();

data.add(e.getMessage());

 

resultMap.put("status", status);

resultMap.put("msg", msg);

resultMap.put("data", data);

return resultMap;

}

Exception이 발생할 때 처리할 Controller도 다른 RestController와 같은 형식을 갖는다. 

 

 

 

HTTP 요청시 Content-Type 

 - text타입 : text/css, text/plain, text/javascript, text/html

 - file : multipart/form-data

 - application : application/json, application/x-www-urlencoded

 

application/json 

{key : value}

 

application/x-www-urlencoded

key=value&key=value

html의 form의 기본 content-type 

'Java > Spring Boot' 카테고리의 다른 글

JPA 계층형 게시판  (0) 2023.10.10
Spring Data JPA begins  (0) 2023.10.06
Spring addViewControllers  (0) 2023.09.14
Thymeleaf in Spring  (0) 2023.09.14
Spring Interceptor  (0) 2023.09.14
728x90

주어진 수까지의 정수 중 소수의 개수 반환

 

public int solution(int n) {

int answer = (n>=2)? 1: 0;

for(int i=3; i<=n;i+=2){

if(isPrime(i)){

answer++;

}

}

return answer;

}

public boolean isPrime(int n){

for(int i=2; i*i<=n;i++){

if(n%i==0){

return false;

}

}

return true;

}

n이 2일땐 소수는 2 자신을 갖고 1이하는 답은 0 이다.

소수를 찾을 때 3부터 찾고

효율성을 위해 소수인지 확인할 때는 i^2이 해당 수까지만 계산한다.

'Java > Coding Test' 카테고리의 다른 글

공원 산책 문제풀이  (0) 2023.09.24
신고 결과 받기 문제풀이  (0) 2023.09.23
소인수분해 문제풀이  (0) 2023.09.18
치킨 쿠폰 문제풀이  (0) 2023.09.17
유한소수 판별하기 문제풀이  (0) 2023.09.17
728x90

주어진 수의 소인수를 오름차순 정렬하여 반환

 

public int[] solution(int n) {

Set<Integer>set = new HashSet<Integer>();

for (int i = 2; i <= n; i++) {

while(n%i==0) {

n/=i;

set.add(i);

}

}

int[] a = new int[set.size()];

Iterator<Integer> it = set.iterator();

for (int i = 0; i < a.length; i++) {

a[i]=it.next();

}

Arrays.sort(a);

return a;

}

2부터 n까지 수를 나누는데 

한번 나눌때 나눠질때까지 계속 나눠야 소인수만 구해진다 그렇지 않으면 소인수의 배수들이 걸러지지 않는다. 

나눌때마다 i를 set에 넣기 때문에 set은 중복을 거르는 Set으로 하였다. 

Set은 순서가 없기 때문에 오름차순 정렬을 위해 배열로 변경하였다.

'Java > Coding Test' 카테고리의 다른 글

신고 결과 받기 문제풀이  (0) 2023.09.23
소수찾기 문제풀이  (0) 2023.09.18
치킨 쿠폰 문제풀이  (0) 2023.09.17
유한소수 판별하기 문제풀이  (0) 2023.09.17
저주의 숫자 3 문제풀이  (0) 2023.09.17

+ Recent posts