본문 바로가기
코테/프로그래머스

배열 뒤집기

by Slow Motion~ 2023. 2. 21.
728x90

C++로 풀었다 처음에 push_back 생각 못해서 temp로 바꿔서 풀려고 했었는데 멍청

 

#include <vector>

using namespace std;

vector<int> solution(vector<int> num_list) {
    vector<int> answer;
    for (int i = num_list.size() - 1; i >= 0; i--) {
        answer.push_back(num_list[i]);
    }
    return answer;
}

자바는  while로 풀었다

class Solution {
    public int[] solution(int[] num_list) {
        int temp;                       // 배열 요소를 교환할 때 사용할 임시 변수
        int start = 0;                  // 배열의 시작 인덱스
        int end = num_list.length - 1;  // 배열의 끝 인덱스

        // 배열 요소를 뒤집는 while 루프
        while (start < end) {
            // 배열의 시작 요소를 임시 변수에 저장하고, 배열의 끝 요소와 교환
            temp = num_list[start];
            num_list[start] = num_list[end];
            num_list[end] = temp;

            // 배열의 시작 인덱스를 증가시키고, 배열의 끝 인덱스를 감소
            start++;
            end--;
        }

        return num_list;  // 뒤집힌 배열을 반환
    }
}

'코테 > 프로그래머스' 카테고리의 다른 글

문자열 뒤집기(for문에 대해)  (0) 2023.02.22
각도기  (0) 2023.02.21
피자 나눠 먹기 (2)  (0) 2023.02.21
피자 나눠먹기 (1)  (0) 2023.02.13
중앙값 구하기  (0) 2023.02.09

댓글