• 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
  • 相关阅读:
    /usr/bin/ld: 找不到 /usr/lib64/libatomic.so.1.0.0
    linux Version mismatch error. This is libtool 2.4.6 Debian-2.4.6-2
    java播放语音文件
    java冒泡排序
    java递归求和
    常见芯片标号说明
    keil5 新建 stm32项目 步骤
    st-link 升级固件时报错“is not in the DFU mode”
    数码管 段选位选
    C51 定时器
  • 原文地址:https://www.cnblogs.com/lcy0515/p/9179745.html
Copyright © 2020-2023  润新知