LeetCode解题路程(5)

258. 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?

这道题以前看到过,作为入门题是很合适的

找规律,发现所有9的倍数的最终位数和一定是9

9 + 9 + 9 = 2 + 7 = 9

且,一个数的位数和能够拆分 f(a) = f(b+c) = f(b) + f(c)

利用这个规律,求9的余数

52 = 45 + 7

7 + 9 = 16, 1+6 =7

发现成为了余数的本身,所以一个数(非0)的位数和要么为9(9的倍数),要么为除以9的余数

通过数学规律能够简化算法,是算法设计的最重要、也是最漂亮的优化

public int addDigits(int num) {
    if(num==0)
        return 0;
    return num%9==0?9:num%9;
}

263. Ugly Number

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

一开始用prime来做,检查是否存在大于5的质因数,时间超了

明显,检查质数用累加的方式是很慢的,考虑用质数表,在数字比较大情况下也非常不好

后来想了下,只需要考虑2,3,5就行了,求出除尽2,3,5的结果是否不等于1应该是最优的解决方法

public boolean isUgly(int num) {
    if(num<=0){
        return false;
    }
    while(num%2==0){
        num/=2;
    }
    while(num%3==0){
        num/=3;
    }
    while(num%5==0){
        num/=5;
    }
    if(num==1){
        return true;
    }else{
        return false;
    }
    
}

303. Range Sum Query - Immutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

这题的测试用例又多又大,很好的考了两点

  • 计算结果保存起来,以供多次调用,减少之后的计算时间
  • 在数组中,sumRange(a,b)最好的求法是使用sumRange(0,b)- sumRange(0,a - 1),这样只需要一维数组保存联系区域的和,在调用函数时做一此运算就行

用二维数组来保存a,b的范围和,结果就超时了

public NumArray(int[] nums) {
    if(nums.length>0){
        rangeSum = new int[nums.length];
        rangeSum[0] = nums[0];
        for(int i=1;i<nums.length;++i){
            rangeSum[i] = rangeSum[i-1]+nums[i];
        }
    }
}

public int sumRange(int i, int j) {
    if(i==0)
        return rangeSum[j];
    else
        return rangeSum[j] - rangeSum[i-1];
}

 

转载于:https://my.oschina.net/u/2486965/blog/749011

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值