leetcode [#172] | GCidea's blog

作者:JerryXia | 发表于 , 阅读 (4)
目录1. 题目2. 解决方案3. 注意事项
题目Given an integer n, return the number of trailing zeroes in n!.
Note:Your solution should be in logarithmic time complexity.
解决方案12345678910public class Solution {    public int trailingZeroes(int n) {        int count = 0;        while(n > 0){            count += n / 5;            n = n / 5;        }        return count;    }}注意事项并不是单纯考察求解某个数的阶乘值,因此没有必要按照给定的n先求出n!是多少,这样的话复杂度也符合o(lgn)的要求。n!值末尾有0,那么必然是2和5相乘得来的(不可能是0本身)。因此,n!末尾有几个0,取决于2的个数和5的个数的最小值。可以得到的结论是,由于2比5小,因此对于任意...阅读全文

leetcode [#171] | GCidea's blog

作者:JerryXia | 发表于 , 阅读 (5)
目录1. 题目2. 解决方案3. 注意事项
题目Given a column title as appear in an Excel sheet, return its corresponding column number.
Note:A -> 1B -> 2C -> 3…Z -> 26AA -> 27AB -> 28 
解决方案1234567public class Solution {    public int titleToNumber(String s) {        double result = 0;        for(int i = 0; i < s.length(); i++) result += Math.pow(26, (s.length() - 1 - i)) * (s.charAt(i) - 'A' + 1);        return (int) result;    }}注意事项遍历字符串,每一位的权重是26的(s.length() - 1 - i)次幂,结果求和即可。...阅读全文

leetcode [#189] | GCidea's blog

作者:JerryXia | 发表于 , 阅读 (4)
目录1. 题目2. 解决方案3. 注意事项
题目Rotate an array of n elements to the right by k steps.
Example:with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
解决方案123456789101112public class Solution {    public void rotate(int[] nums, int k) {        int len = nums.length;        int[] result = new int[len];        for(int p = 0; p < len; p++){            result[p] = nums[(len...阅读全文

leetcode [#19] | GCidea's blog

作者:JerryXia | 发表于 , 阅读 (6)
目录1. 题目2. 解决方案3. 注意事项
题目Given a linked list, remove the nth node from the end of list and return its head.
Example:Given linked list: 1->2->3->4->5, and n = 2.After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:Given n will always be valid.Try to do this in one pass.
解决方案12345678910111213141516171819202122232425262728293031323334353637/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) ...阅读全文

leetcode [#179] | GCidea's blog

作者:JerryXia | 发表于 , 阅读 (6)
目录1. 题目2. 解决方案3. 注意事项
题目Given a list of non negative integers, arrange them such that they form the largest number.
Example:Given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note:
The result may be very large, so you need to return a string instead of an integer.解决方案123456789101112131415161718192021222324252627282930313233343536373839public class Solution {    public String largestNumber(int[] nums) {        //如果为空,直接返回空串        if(nums == null || nums.length == 0)            re...阅读全文