[Java, JS]_2467_용액

hanseungjune·2023년 6월 25일
0

알고리즘

목록 보기
15/33
post-thumbnail

작성 코드

import java.io.*;
import java.util.*;

public class solution_2467 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());
        int[] solution = Arrays.stream(br.readLine().split(" ")).mapToInt(item -> Integer.parseInt(item)).toArray();

        Arrays.sort(solution);

        int left = 0;
        int right = n - 1;
        int diff = Math.abs(solution[left] + solution[right]);
        int[] diff_match = {solution[left], solution[right]};

        while (left < right) {
            int sum_val = solution[left] + solution[right];
            if (Math.abs(sum_val) < diff) {
                diff = Math.abs(sum_val);
                diff_match[0] = solution[left];
                diff_match[1] = solution[right];
            }

            if (sum_val < 0) {
                left++;
            } else if (sum_val > 0) {
                right--;
            } else {
                break;
            }
        }

        System.out.println(diff_match[0] + " " + diff_match[1]);
    }
}

설명

해당 코드는 정렬된 배열에서 두 수의 합이 0에 가장 가까운 값을 찾는 문제를 해결하는 코드입니다. 자료구조로는 정수형 배열 solution, 정수형 변수 left, right, diff 그리고 정수형 배열 diff_match를 사용합니다.

solution: 입력으로 받은 정수 배열을 나타냅니다.
left: 배열의 가장 왼쪽 인덱스를 나타내는 변수입니다.
right: 배열의 가장 오른쪽 인덱스를 나타내는 변수입니다.
diff: 현재까지 찾은 두 수의 합과 0의 차이를 저장하는 변수입니다.
diff_match: 두 수의 합이 0에 가장 가까운 값을 저장하는 배열입니다.
해당 코드의 로직은 다음과 같습니다.

입력으로 받은 n 값을 읽고, 배열 solution을 입력받습니다.
배열 solution을 정렬합니다.
변수 left를 0으로, 변수 right를 n-1로 초기화합니다.
변수 diffsolution[left]solution[right]의 합의 절댓값으로 초기화합니다.
diff_match 배열을 [solution[left], solution[right]]로 초기화합니다.
leftright보다 작은 동안 아래의 과정을 반복합니다.
현재 leftright 인덱스에 위치한 두 수의 합을 sum_val 변수에 저장합니다.
sum_val의 절댓값이 diff보다 작다면, diffdiff_match 값을 갱신합니다.
sum_val이 0보다 작다면, left를 1 증가시킵니다.
sum_val이 0보다 크다면, right를 1 감소시킵니다.
sum_val이 0과 같다면, 반복문을 종료합니다.
diff_match 배열의 값을 출력합니다.
따라서 해당 코드는 주어진 정렬된 배열에서 두 수의 합이 0에 가장 가까운 값을 찾아 출력하는 코드입니다.

자바스크립트

const readline = require("readline");

const input = [];
let n = null;

readline
  .createInterface(process.stdin, process.stdout)
  .on("line", (line) => {
    if (!n) {
      n = parseInt(line);
    } else {
      input.push(...line.split(" ").map(Number));
    }
  })
  .on("close", () => {
    const solution = input;
    solution.sort((a, b) => a - b);

    let left = 0;
    let right = n - 1;
    let diff = Math.abs(solution[left] + solution[right]);
    let diff_match = [solution[left], solution[right]];

    while (left < right) {
      let sum_val = solution[left] + solution[right];
      if (Math.abs(sum_val) < diff) {
        diff = Math.abs(sum_val);
        diff_match = [solution[left], solution[right]];
      }

      if (sum_val < 0) {
        left++;
      } else if (sum_val > 0) {
        right--;
      } else {
        break;
      }
    }

    console.log(diff_match.join(" "));
    process.exit();
  });

파이썬

import sys
input = sys.stdin.readline

n = int(input())
solution = list(map(int, input().split()))
solution.sort()

left = 0
right = n - 1
diff = abs(solution[left] + solution[right])
diff_match = [solution[left], solution[right]]

while left < right:
    sum_val = solution[left] + solution[right]
    if abs(sum_val) < diff:
        diff = abs(sum_val)
        diff_match = [solution[left], solution[right]]
    
    if sum_val < 0:
        left += 1
    else:
        right -= 1
        
print(diff_match[0], diff_match[1])
profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글