Tìm các số bị trùng trong một mảng số trong Java. (How to find duplicates numbers of number array in Java?)







Tìm các số bị trùng(duplicates) trong một mảng là một bài tập điển hình trong Java, bài viết này sẽ hướng dẫn một cách đơn giản để tìm kiếm các giá trị số bị trùng trong một mảng số(array number).






FindDupNumberInArray.java
/**
 * @(#)FindDupNumberInArray.java
 *
 * FindDupNumberInArray application
 *
 * @author developer.bnson@gmail.com
 * @version 1.00 2014/3/9
 */


import java.util.ArrayList;
import java.util.List;

public class FindDupNumberInArray {
   
    public static void main(String[] args) {
       
        int[] arrInt = new int[15];
       
        for (int i = 0; i < arrInt.length-5; i++) {
            arrInt[i] = i;
        }
       
        //Add duplicate to array.
        arrInt[10] = 1;
        arrInt[11] = 7;
        arrInt[12] = 3;
        arrInt[13] = 6;
        arrInt[14] = 9;
       
        //Print list number in array.
        System.out.print("Array: [ ");
        for (int tmp : arrInt) {
            System.out.print(tmp + " ");
        }
        System.out.print("] \n");
       
        //Call function findDup.
        findDup(arrInt);
    }
   
    private static void findDup(int[] arrInt)
    {
        List<Integer> listIntWithoutDup = new ArrayList<Integer>();
       
        for(int tmp : arrInt) {
            if(listIntWithoutDup.contains(tmp)) {
                System.out.println( "This is duplicate: " + tmp);               
            } else {
                 listIntWithoutDup.add(tmp);
            }
        }
       
        System.out.println("\n Copyright © VN-Lives");
    }   
   
}
Sau khi chạy chương trình bảng sẽ được kết quả như sau:

Array: [ 0 1 2 3 4 5 6 7 8 9 1 7 3 6 9 ]
This is duplicate: 1
This is duplicate: 7
This is duplicate: 3
This is duplicate: 6
This is duplicate: 9

 Copyright © VN-Lives

Trong đoạn mã trên tôi sử dụng List để chuyển các giá trị trong Array(chứa giá trị dãy số cần kiểm tra trùng), nhưng trước khi đưa các giá trị vào List tôi sẽ kiểm tra xem giá trị đó có tồn tài trong List chưa, nếu có tức là giá trị này bị trung trong Array, ngược thì tôi sẽ add giá trị không bị dup vào List, và điều này giúp ta giải quyết được bài toán.

























No comments:

Post a Comment