본문 바로가기
Coding Test/프로그래머스

[프로그래머스] Lv.1 두 개 뽑아서 더하기

by CSEGR 2024. 2. 26.
728x90

➕ArrayList 이용 

 

<문제 설명>

정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요.

 

제한사항

  • numbers의 길이는 2 이상 100 이하입니다.

입출력 예

numbers result
[2,1,3,4,1] [2,3,4,5,6,7]
[5,0,2,7] [2,5,7,9,12]

 

 

이 문제의 핵심은 중복된 수를 어떻게 빼느냐이다. 

처음엔 어떻게 중복된 수를 뺄까 고민을 하다가 ArrayList 을 알게되었다. 

 

🟣ArrayList 

 ➜ 특징 

    - ArrayList 클래스는 내부적으로 Object[] 배열 이용 = 인덱스를 이용해 요소에 빠르게 접근 가능

    - 동적 배열 : 크기가 고정되어 있는 배열과 달리 가변적으로 공간을 늘리거나 줄임

    

 ➜ 선언 방법 

import java.util.ArrayList;

//Integer로 타입설정 , int형 객체만 적재가능 
ArrayList<Integer> arr = new ArrayList<>();

//String로 타입설정, String형 객체만 적재가능
ArrayList<String> str = new ArrayList<>();

 

 ➜요소 삽입  : add() 이용 

void add(int index, Object element) 

- 지정된 위치(index)에 요소 삽입

- 지정된 위치에 있던 기존 데이터는 뒤로 밀려나감(삭제되지 않음)

ArrayList<String> str = new ArrayList<>();
str.add("hello");

 

 ➜ 요소 삭제  : remove()

ArrayList<String> str = new ArrayList<>(8); 

str.add("hello");
str.add("world");

// 1번째 인덱스 자리의 요소 삭제
str.remove(1);

 

➜ 요소 검색 : contains(), indexOf()

ArrayList<String> str = new ArrayList<>();
str.add("A");
str.add("B");
str.add("C");
str.add("D");

// str에 A가 있는지 검색 : true
str.contains("A"); 

// str에 A가 있는지 순차적으로 검색하고 index를 반환 (없으면 -1)
str.indexOf("A"); // 0

 

➜ 요소 얻기 : get()

ArrayList<String> str = new ArrayList<>(18); 

str.add("1");
str.add("2");
str.add("3");
str.add("4");
str.add("5");

str.get(0); // "1"
str.get(3); // "4"

 

➜ 순회 

ArrayList<Integer> str = new ArrayList<Integer>();
str.add(1);
str.add(2);

for(Integer i : str) { 
    System.out.println(i);
}

 

 

<구현> 

1. ArrayList 선언 

2. 두 수의 합이 ArrayList에 포함되어 있는지 contains 함수로 확인 (없으면 추가)

3. ArrayList의 원소를 얻기 위해 get()함수 이용하여 리스트에 삽입

4. 리스트 오름차순 정렬하기 위해 sort 함수 사용 

import java.util.ArrayList;
import java.util.Arrays;
class Solution {
    public int[] solution(int[] numbers) {
        ArrayList<Integer> list = new ArrayList<>();
        int size = numbers.length; 
        int temp;
        
        for(int i = 0; i<size; i++){
            for(int j = i+1; j<size; j++)
            {
                temp = numbers[i] + numbers[j];
                if(list.contains(temp)) continue;
                list.add(temp);
            }
        }
        
        int[] answer = new int[list.size()];
        for(int i = 0; i<list.size(); i++)
        {
            answer[i] = list.get(i);
        }
        
        Arrays.sort(answer);
        
        return answer;
    }
}

 

 

 

 

<출처>

https://inpa.tistory.com/entry/JAVA-☕-ArrayList-구조-사용법

728x90