欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字

程序员文章站 2022-03-08 15:32:58
...
package demo;

import java.util.Arrays;

/*
 * 题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
 */
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Offer_24 {
    public void FindNumsAppearOnce(int[] array, int num1[], int num2[]) {
        Arrays.sort(array);
        for (int i = 0; i < array.length; i += 2) {
            if (array[i] != array[i + 1]) {
                num1[0] = array[i];
                break;
            }
        }
        for (int j = array.length - 1; j < array.length; j -= 2) {
            if (array[j] != array[j - 1]) {
                num2[0] = array[j];
                break;
            }
        }
    }
    public static void main(String[] args) {
        Offer_24 off = new Offer_24();
        int array[] = {1,1,2,3,4,4};
        int num1[]=new int [1];
        int num2[]=new int [1];
        off.FindNumsAppearOnce(array, num1, num2);
        System.out.println(num1[0]);
        System.out.println(num2[0]);
    }
}