Skip to Content
CoursesCSC102การหาตัวเลขที่ปรากฏเพียงครั้งเดียวในอาเรย์

การหาตัวเลขที่ปรากฏเพียงครั้งเดียวในอาเรย์

โจทย์

You are given an array of integers, where all elements but one occur twice. Your task is to find the unique element that occurs only once in the array.

Input:

  • The first line contains a single integer, nn, the number of integers in the array. The second line contains nn space-separated integers that describe the values in the array.

Output:

  • Return a single integer representing the element that occurs only once.

Explanation:

  • In the array, all elements occur twice except for the number 3, which occurs only once.
InputOutput
7
1 1 2 3 2 4 4
3

โค้ด

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int size = scanner.nextInt(); int[] memorized = new int[1000]; for (int i = 0; i < size; i++) { int number = scanner.nextInt(); memorized[number]++; } for (int i = 0; i < memorized.length; i++) { if (memorized[i] == 1) { System.out.println(i); } } } }

คำอธิบาย

1. การประกาศคลาสและรับขนาดอาเรย์

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int size = scanner.nextInt(); // รับขนาดของอาเรย์

2. การสร้างและใช้อาเรย์นับความถี่

int[] memorized = new int[1000]; // สร้างอาเรย์เก็บความถี่ for (int i = 0; i < size; i++) { int number = scanner.nextInt(); // รับตัวเลข memorized[number]++; // เพิ่มความถี่ของตัวเลขที่พบ }
  • สร้างอาเรย์ขนาด 1000 เพื่อเก็บความถี่
  • ใช้ตัวเลขเป็น index ในการนับความถี่
  • เพิ่มค่าในตำแหน่งที่ตรงกับตัวเลขที่พบ

3. การค้นหาและแสดงตัวเลขที่ปรากฏครั้งเดียว

for (int i = 0; i < memorized.length; i++) { if (memorized[i] == 1) { // ถ้าพบตัวเลขที่มีความถี่เท่ากับ 1 System.out.println(i); // แสดงตัวเลขนั้น } }
  • วนลูปตรวจสอบอาเรย์ความถี่
  • ถ้าพบตำแหน่งที่มีค่าเท่ากับ 1 แสดงว่าตัวเลขนั้นปรากฏครั้งเดียว
  • แสดงค่า index ที่เป็นตัวเลขที่ปรากฏครั้งเดียว

แผนภาพการทำงาน

ตัวอย่างการทำงาน

ตัวอย่างที่ 1

Input: 5 1 2 1 3 2 การทำงาน: 1. สร้างอาเรย์ความถี่: [0, 0, 0, 0, ...] (ขนาด 1000) 2. นับความถี่: พบ 1: memorized[1]++ → 1 พบ 2: memorized[2]++ → 1 พบ 1: memorized[1]++ → 2 พบ 3: memorized[3]++ → 1 พบ 2: memorized[2]++ → 2 3. อาเรย์ความถี่หลังนับ: index: 0 1 2 3 4 ... value: 0 2 2 1 0 ... 4. ตรวจพบ memorized[3] = 1 Output: 3

ตัวอย่างที่ 2

Input: 3 4 1 4 การทำงาน: 1. นับความถี่: พบ 4: memorized[4]++ → 1 พบ 1: memorized[1]++ → 1 พบ 4: memorized[4]++ → 2 2. อาเรย์ความถี่: index: 0 1 2 3 4 ... value: 0 1 0 0 2 ... Output: 1
ปรับปรุงล่าสุด