zoukankan      html  css  js  c++  java
  • Java中找出缺失的数字

    给定一组连续的整数,例如:10,11,12,……,20,但其中缺失一个数字,试找出缺失的数字
    1
    import java.util.*; 2 3 public class Main { 4 public static void main(String[] args) { 5 // 构造从start到end的序列: 6 final int start = 10; 7 final int end = 20; 8 List<Integer> list = new ArrayList<>(); 9 for (int i = start; i <= end; i++) { 10 list.add(i); 11 } 12 // 随机删除List中的一个元素: 13 int removed = list.remove((int) (Math.random() * list.size())); 14 int found = findMissingNumber(start, end, list); 15 System.out.println(list.toString()); 16 System.out.println("missing number: " + found); 17 System.out.println(removed == found ? "测试成功" : "测试失败"); 18 }

        //以下为算法的核心方法
    19 static int findMissingNumber(int start, int end, List<Integer> list) { 20 int found = 0 ; 21 for(int i = start; i< end; i++){ 22 if(list.get(i-10) != i){ 23 found = i; 24 break; 25 } 26 } 27 return found; 28 } 29 }

    引用:https://www.liaoxuefeng.com/wiki/1252599548343744/1265112034799552

    2. 还可以用求合法,两个数组分别求和,再相减,得出的就是缺少的数,很简单。代码如下:

    static int findMissingNumber(int start, int end, List<Integer> list) {
    //求合法
    int sum1 = 0;
    int sum2 = 0;
    for(int i = start; i<= end;i++){
    sum1 +=i;
    }
    for(Integer in : list){
    sum2 += in;
    }
    System.out.println(sum1-sum2);
    return Math.abs(sum1-sum2);
    }

    3.最简单的方法:用list.contains();方法判断

    static int findMissingNumber(int start, int end, List<Integer> list) {
    int missNum = 0;
    for(int i = start; i<= end; i++){
    if( ! list.contains(i) ){
    missNum = i;
    }
    }
    return missNum;
    }

  • 相关阅读:
    mac 10.9 安装 gevent
    flash builder4.7 for Mac升级AIRSDK详解
    重走java--Step 3
    重走java--Step 2
    重走java---Step 1
    web初学之MVC
    web初学之JavaBean
    微信公众号开发之开发模式的启用——学习笔记
    微信公众号开发之开通账号——学习笔记
    web初学之request,session与application
  • 原文地址:https://www.cnblogs.com/gslgb/p/12795225.html
Copyright © 2011-2022 走看看