zoukankan      html  css  js  c++  java
  • Leetcode 2

    Array Easy 

    1.  66. Plus One

      从后向前遍历,两种情况:

         ① digits[ i ] < 9, 则加1并直接返回。

         ② 此位为9,赋值为0,并继续循环。

      考虑特殊情况,所有位都是9,如9999,则结束循环时设置一个大一位的新数组并且第一个位置赋值为1。

     

    class Solution {
        public int[] plusOne(int[] digits) {
            int n = digits.length;
            
            for(int i = n-1; i>=0; i--){
                if(digits[i] < 9){
                    digits[i]++;
                    return digits;
                }
                else{
                    digits[i] = 0;
                }
            }
            
            int[] res = new int[n+1];
            res[0] = 1;
            return res;
        }
    }

     2. 118. Pascal's Triangle

      杨辉三角

       从前向后遍历:

      for(int j=1;j<row.size()-1;j++)
    	row.set(j, row.get(j)+row.get(j+1)); 必须是 row.add(0, 1);

    3. 119. Pascal's Triangle II 

      要求返回给定索引层的数据。

      一维数组就可以满足需求,并且在第二层循环中采用倒叙遍历的方式 res.set(j, res.get(j-1) + res.get(j)); 且必须是 row.add(1); 添加边界值1到最后。

      注意第一层边界的终止条件到 i <= rowIndex 即可。

      

    class Solution {
        public List<Integer> getRow(int rowIndex) {
            List<Integer> res = new ArrayList<Integer>();
            
            for(int i = 0; i <= rowIndex ; i++){
                res.add(1);
                for (int j = i - 1 ; j > 0 ; j--){
                    res.set(j, res.get(j-1) + res.get(j)); //
                }
            }
            return res;
        }
    }
  • 相关阅读:
    cesium 之图层管理器篇(附源码下载)
    cesium 之三维场景展示篇(附源码下载)
    InfluxDB 常用命令
    开始使用Chronograf(官方说明)
    InfluxDB(官方使用说明)
    centos su命令
    CentOS7使用firewalld打开关闭防火墙与端口
    HBase教程
    OpenTSDB安装
    OpenTSDB(时序数据库官网)
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/10731958.html
Copyright © 2011-2022 走看看