강의

멘토링

커뮤니티

Inflearn Community Q&A

No author

This post's author information has been deleted.

Introduction to Algorithm Problem Solving for IT Employment (with C/C++): Coding Test Preparation

37. Least Recently Used (Insertion Sort Code Style)

배열의 처음부터 접근해도 괜찮을까요?

Written on

·

236

0

 

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <vector>
#include <algorithm>

int main()
{
	freopen("input.txt", "rt", stdin);

	int cacheSize, tasks;

	scanf("%d %d", &cacheSize, &tasks);

	std::vector<int> cacheList(cacheSize, 0);

	int i = 0;
	for (int task = 0; task < tasks; task++)
	{
		if (i != cacheSize-1)
		{
			i++;
		}
		int k;
		int input;
		int pos = 0;
		scanf("%d", &input);

		// Hit 위치를 찾아낸다.
		for (k = 0; k <= i; k++)
		{
			if (cacheList[k] == input)
			{
				pos = k;
			}
		}

		// Hit가 없으면
		if (pos == 0)
		{
			for (k = i - 1; k >= 0; k--)
			{
				cacheList[k + 1] = cacheList[k];
			}
		}
		else
		{
			for (k = pos - 1; k >= 0; k--)
			{
				cacheList[k + 1] = cacheList[k];
			}
		}
		cacheList[k + 1] = input;
	}

	for (int i = 0; i < cacheSize; i++)
	{
		printf("%d ", cacheList[i]);
	}

	return 0;
}

 

반복횟수를 줄여보고자 첫 인덱스부터 접근했보았습니다.

괜찮은 코드일까요?

 

C++코테 준비 같이 해요!

Answer 1

1

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

네. 좋은 코드입니다.

No author

This post's author information has been deleted.

Ask a question