首页 > 其他 > 详细

Leetcode 2

时间:2019-04-18 20:18:27      阅读:109      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

Leetcode 2

原文:https://www.cnblogs.com/Afei-1123/p/10731958.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!