-
K번째 수알고리즘/알고리즘 문제 복기 2021. 2. 3. 12:03
programmers.co.kr/learn/courses/30/lessons/42748
코딩테스트 연습 - K번째수
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]
programmers.co.kr
문제
내 풀이
1234567891011121314151617181920212223242526#include <string>#include <vector>#include <algorithm>#include <iostream>using namespace std;vector<int> solution(vector<int> array, vector<vector<int>> commands) {vector<int> answer;vector<int> sliced_array;// commands[i][0] == first index + 1;// commands[i][1] == second index + 1;// commands[i][2] == picking point + 1;for(int i = 0; i < commands.size(); ++i) {sliced_array = {};for(int j = commands[i][0] - 1; j < commands[i][1]; j++) {sliced_array.push_back(array[j]);}sort(sliced_array.begin(), sliced_array.end());answer.push_back(sliced_array[commands[i][2]-1]);}return answer;}cs commands가 이중 for문으로 주어졌기 때문에
2중 for문 안에 들어가 있는 j의 값을 통해 input되어진 array를 슬라이스했고
그 뒤에 sort를 하여 답을 구해냈다.
다른 사람의 풀이
123456789101112131415161718#include <string>#include <vector>#include <algorithm>using namespace std;vector<int> solution(vector<int> array, vector<vector<int>> commands) {vector<int> answer;vector<int> temp;for(int i = 0; i < commands.size(); i++) {temp = array;sort(temp.begin() + commands[i][0] - 1, temp.begin() + commands[i][1]);answer.push_back(temp[commands[i][0] + commands[i][2]-2]);}return answer;}cs 2중 for문의 슬라이싱 하는 부분을
sort 함수의 temp.begin() 인수에 command 값을 더해줬다.
'알고리즘 > 알고리즘 문제 복기' 카테고리의 다른 글
Leetcode - 17. Letter Combination of a Phone Number (0) 2021.02.13 Leetcode - 15. 3Sum (0) 2021.02.13 Leet code - 2. Add Two Number (0) 2021.02.08 Leet code - 1. Two Sum (0) 2021.02.06 Leecode - 5. Logest Palindromic SubString (0) 2021.02.06