Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- SQL
- 코딩테스트
- two pointers
- hash table
- Class
- 파이썬
- bit manipulation
- geometry
- dynamic programming
- array
- Stack
- 구현
- 자바
- Method
- database
- string
- Number Theory
- Counting
- Data Structure
- Tree
- simulation
- sorting
- Math
- Binary Tree
- Binary Search
- implement
- 코테
- Matrix
- java
- greedy
Archives
- Today
- Total
코린이의 소소한 공부노트
[프로그래머스/Lv.0] 무작위로 K개의 수 뽑기 본문
1. Input, Output, Example
랜덤으로 서로 다른 k개의 수를 저장한 배열을 만드려고 한다. 적절한 방법이 떠오르지 않기 때문에 일정한 범위 내에서 무작위로 수를 뽑은 후, 지금까지 나온적이 없는 수이면 배열 맨 뒤에 추가하는 방식으로 만들기로 한다. 이미 어떤 수가 무작위로 주어질지 알고 있다고 가정하고, 실제 만들어질 길이 k의 배열을 예상해보자.
- 문제에서의 무작위의 수는 arr에 저장된 순서대로 주어질 예정이라고 했을 때, 완성될 배열을 반환
2. Constraint
1) 1 ≤ arr의 길이 ≤ 100,000
2) 0 ≤ arr의 원소 ≤ 100,000
3) 1 ≤ k ≤ 1,000
3. Code
1) 첫 코드(2023/04/27)
import java.util.*;
class Solution {
public int[] solution(int[] arr, int k) {
int[] answer = new int[k];
ArrayList<Integer> list = new ArrayList<>();
int i = 0;
while(list.size()<k && i<arr.length){
if(!list.contains(arr[i]))
list.add(arr[i]);
i++;
}
for(i=0 ; i<list.size() ; i++)
answer[i] = list.get(i);
if(list.size()!=k)
for(i=list.size() ; i<k ; i++)
answer[i] = -1;
return answer;
}
}
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[LeetCode/Easy] 2190. Most Frequent Number Following Key In an Array (0) | 2023.04.27 |
---|---|
[LeetCode/Easy] 2133. Check if Every Row and Column Contains All Numbers (0) | 2023.04.27 |
[프로그래머스/Lv.0] 배열 만들기 4 (0) | 2023.04.27 |
[프로그래머스/Lv.0] qr code (0) | 2023.04.27 |
[프로그래머스/Lv.0] 왼쪽 오른쪽 (0) | 2023.04.27 |