zoukankan      html  css  js  c++  java
  • [LeetCode]Missing Number

    题目:Missing Number

    给定一个从0,1,2,...,n中取出的n个不同数字的数组,找到数组中缺少的数字。

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

    For example,
    Given nums = [0, 1, 3] return 2.

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

    要求:线性时间复杂度O(n)和常数空间复杂度O(1)。

    思路:

    [0,n]的和很好求,用等差数列的求和公式,就能求出

    sumn = max*(max + 1) / 2;

    然后求出数组实际的和,相减就能求出缺失的数字。

    int LeetCode::missingNumber(vector<int>& nums){
        int sum = 0,sumn = 0;//sum是数组的和,sumn是[0,n]的和
        int max = nums.size();//数组的最大值
        for (auto i : nums)sum += i;//求和
        sumn = max*(max + 1) / 2;
        return sumn - sum;
    }

    题目:Add Digits

    Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

    For example:

    Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

    Follow up:
    Could you do it without any loop/recursion in O(1) runtime?

    给定非负整数num,将其所有位数的数字重复相加,直到结果只有一位数字。

    要求:不用循环和递归,时间复杂度O(1)

    思路:

    通常思路按照求和的方式,相加知道符合要求,但是,这样必须使用循环或递归。

    int LeetCode::addDigits(int num){
        if (num < 0)return -1;
        /*循环求解*/
        while (num >= 10){//是否小于10
            int add = 0;
            while (num){//按位求和
                add += num % 10;
                num /= 10;
            }
            num = add;
        }
        return num;
    }

    思路:

    如何不用循环和递归求解呢?

    不妨设num = 100*a + 10*b + c,那么一次求和是a+b+c;

    num = 99*a + a + 9*b + b + c = (99*a + 9*b) + (a+ b +c);只要去掉前面括号的部分就可以了。

    即有 num%9;实际上,任何数字的按位和都可以这样,它最终求的结果是个位数,因此可以直接求出结果。

    int LeetCode::addDigits(int num){
        if (num < 0)return -1;
        //若num = 100a+10b+c,则(100a+10b+c)%9=(a+99a+b+9b+c)%9=(a+b+c)%9
        if (!num)return 0;
        if (num % 9)return num % 9;
        return 9;
    }
  • 相关阅读:
    JDK介绍
    选择器——过滤选择器——内容过滤器
    选择器——过滤选择器——基本过滤器
    选择器——层次选择器
    选择器——基本选择器
    jQuery 对象转成 DOM 对象
    dom转换成jquery对象
    Android-bindService本地服务-初步-Service返回对象
    Android-bindService本地服务-初步
    Android-Service生命周期
  • 原文地址:https://www.cnblogs.com/yeqluofwupheng/p/6821489.html
Copyright © 2011-2022 走看看