《Java面试试题》找出连续数组中相同的两个数值

13 篇文章 0 订阅

如题:
Find out duplicate number between 1 to N numbers.
描述:
You have got a range of numbers between 1 to N, where one of the number is repeated. You need to write a program to find out the duplicate number.
代码:

package test;

import java.util.ArrayList;
import java.util.Iterator;

/*
 *  You have got a range of numbers between 1 to N, where one of the number is repeated. 
 *  You need to write a program to find out the duplicate number.
 */
public class DuplicateNumber {
    /*
     *  1, 2, 2, 3, 4 ---- Duplicated List
     *  Sum(Duplicated List) - 4*5/2 = 2
     */
    public int findDuplicatNumber(ArrayList<Integer> numberList){
        // If there exists a duplicated number, the biggest number in the list is size-1;
        int biggestNum = numberList.size() - 1;
        // 2S = n*(n+1)
        int duplicatedNum = sumList(numberList) - biggestNum*(biggestNum+1)/2;
        return duplicatedNum;
    }

    // get the summation of the list
    public int sumList(ArrayList<Integer> numberList){
        int sum = 0;
        for (int num : numberList) {
            sum += num;
        }
        return sum;
    }

    public static void main(String[] args) {
        ArrayList<Integer> numberArrayList = new ArrayList<Integer>();
        for (int i = 1; i <= 20; i++) {
            numberArrayList.add(i);
        }
        numberArrayList.add(10);
        DuplicateNumber dumTest = new DuplicateNumber();
        System.out.println(dumTest.findDuplicatNumber(numberArrayList));
    }


}

使用数组的前N项和公式,然后根据连续的特性,利用差值求出数组中重复的数据。
要点
1. Java数组的ArrayList使用方法
2. 数组求和的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值