홍시홍의 프로그래밍

[프로그래머스] k번째 수 본문

알고리즘 문제풀이/프로그래머스

[프로그래머스] k번째 수

홍시홍 2020. 4. 18. 19:12

분류 : 정렬

 

요구사항

index (x,y)의 사이에 있는 수 중 k번째 수 구하기

 

풀이

(x,y)번째 중 k번째 수는

오름 차순 정렬 한 후, 원래 인덱스에서의 위치가 (x,y) 사이라면 cnt를 증가 시킨다.

cnt가 k일경우, 정답 출력

 

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

struct go {
	int num;
	int index;
};

bool com(go a, go b) {
	if (a.num < b.num) return true;
	return false;
}
vector<int> solution(vector<int> array, vector<vector<int>> commands) {
	vector<int> answer;
	vector<go> myarray;
	for (int i = 0; i < array.size(); i++) {
		myarray.push_back({ array[i],i+1 });
	}
	sort(myarray.begin(), myarray.end(), com);
	for (int i = 0; i < myarray.size(); i++) {
		cout << myarray[i].num << " ";
	}
	cout << endl;
	for (int i = 0; i < commands.size(); i++) {
		int x = commands[i][0];
		int y = commands[i][1];
		int z = commands[i][2];
		int cnt = 0;
		for (int j = 0; j < myarray.size(); j++) {
			int index = myarray[j].index;
			int num = myarray[j].num;
			cout << "x" << x << "Y" << y << "index" << index << endl;
			if (index >= x && index <= y) {
				cnt++;
			}
			if (cnt == z) {
				answer.push_back(num);
				break;
			}
		}

	}
	return answer;
}
Comments