• Home

My Codegate

  • Home

프로그래머스 같은 숫자는 싫어 자바 문제풀이

2023/12/12 Posted by Codegate Java No Comments
프로그래머스 같은 숫자는 싫어 자바 문제풀이

문제 링크

int[] 배열을 받아서 받은 순서대로 하나씩 뽑되 현재 값과 중복된 값일 경우에는 뽑지 않고 다른 경우에만 뽑아준 뒤 int[] 배열 형태로 반환해주면 되는 문제인데

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class HateSameNumber {

  public static int[] solution(int[] arr) {
    Queue<Integer> queue = new ArrayDeque<>();
    LinkedList<Integer> list = new LinkedList<>();
    for (int j : arr) {
      queue.add(j);
    }
    int current = queue.poll();
    list.add(current);
    while (!queue.isEmpty()) {
      if (current != queue.peek()) {
        current = queue.poll();
        list.add(current);
      } else {
        queue.poll();
      }
    }

    return list.stream().mapToInt(Integer::intValue).toArray();
  }

  public static void main(String[] args) {
    int[] arr = {4, 4, 4, 3, 3};
    System.out.println(Arrays.toString(solution(arr)));
  }
}

Queue에 받은 int[] 배열을 모두 넣어주고 list에 queue에서 뽑은 값을 넣어줘야 하는데, 처음에는 중복될 수 없기 때문에 while 전에 넣어주고 이후 while문으로 queue가 빌때까지 돌려주되, 가장 마지막에 들어간 값과 다를 경우에만 list에 넣어주면 된다.

이후 list를 int[] 배열로 바꿔준 뒤 return 해주면 끝이다.

No Comments
0

Leave a Reply Cancel Reply

Introduction

My Codegate

Latest Posts

  • Google Search Console API 연동방법
  • 인텔리제이 Gradle Dependency 최신 버전 보는 방법
  • Wallet-Tracker 개발일지
  • Moralis API 자바로 호출방법
  • IntelliJ Commit 후 Push 따로 하는 방법

Categories

  • My Project (4)
  • Java (42)
  • Algorithm (161)
    • Java (152)
    • Algorithm Knowledge (3)
    • Algorithm site usage (6)
  • Vue.js (1)
  • Spring (4)
  • Docker (2)
  • IntelliJ (20)
  • Uncategorized (7)

Recent Comments

  • Codegate on Hello world!
  • A WordPress Commenter on Hello world!

© 2025 — mycodegate.com

Prev Next