zoukankan      html  css  js  c++  java
  • 268. Missing Number

    题目地址:https://leetcode.com/problems/missing-number/description/

    Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

    Example 1:

    Input: [3,0,1]
    Output: 2
    

    Example 2:

    Input: [9,6,4,2,3,5,7,0,1]
    Output: 8
    

    Note:
    Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

    class Solution {
        public int missingNumber(int[] nums) {
            int sum = (nums.length + 1) * nums.length >>> 1; // 原本应该nums.length+1个数字,从0到nums.length,求和就行
            int sum1 = 0;
            for (int i = 0; i < nums.length; ++i) {
                sum1 += nums[i];
            }
            return sum - sum1;
        }
    }


    (CSDN的java模版是无法打出null的,不信你们去试试,反映给技术部无果,估计他们也解决不了)

    Debug code in playground: 

    class Solution {
        public int missingNumber(int[] nums) {
            int sum = (nums.length + 1) * nums.length >>> 1;
            int sum1 = 0;
            for (int i = 0; i < nums.length; ++i) {
                sum1 += nums[i];
            }
            return sum - sum1;
        }
    }
    
    public class MainClass {
        public static int[] stringToIntegerArray(String input) {
            input = input.trim();
            input = input.substring(1, input.length() - 1);
            if (input.length() == 0) {
              return new int[0];
            }
        
            String[] parts = input.split(",");
            int[] output = new int[parts.length];
            for(int index = 0; index < parts.length; index++) {
                String part = parts[index].trim();
                output[index] = Integer.parseInt(part);
            }
            return output;
        }
        
        public static void main(String[] args) throws IOException {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String line;
            while ((line = in.readLine()) != null) {
                int[] nums = stringToIntegerArray(line);
                
                int ret = new Solution().missingNumber(nums);
                
                String out = String.valueOf(ret);
                
                System.out.print(out);
            }
        }
    }


    ========================================Talk is cheap, show me the code=======================================

    CSDN博客地址:https://blog.csdn.net/qq_34115899
  • 相关阅读:
    一个从excel导入数据错位问题
    Chrome F12 温故而知新 :因为重定向导致清空Network信息
    export / import 温故而知新
    Chrome Debugger 温故而知新:上下文环境
    微信导出表情包教程
    Oracle中判断字段是否为数字
    获取GridView中RowCommand的当前索引行
    Oracle SQL常用内置系统函数总结
    使用Task代替ThreadPool和Thread
    Visual Studio 使用及调试必知必会
  • 原文地址:https://www.cnblogs.com/lcy0515/p/9179745.html
Copyright © 2011-2022 走看看