leetCode刷题记录二

1、gas-station

There are N gas stations along a circular route, where the amount of gas at station i isgas[i].
You have a car with an unlimited gas tank and it costscost[i]of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station’s index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
法一:预处理gas[i]-cost[i],排序,每次取最大的剩余汽油。
汽油剩余越多当前越好走接下来的路。
法二:先选定一个开始位置,如果我们往下走,若油不够的话,那我们边把开始位置往前挪一个位置。
例如6->0->1 的时候汽油不够那么就变成,5->6->0->1 以此类推。

public class _47 {
    class o{
        int ex;
        int index;
        public o(int ex, int index) {
            this.ex = ex;
            this.index = index;
        }
    }

    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n=gas.length;
        List<o> queue=new ArrayList<o>();
        int[] ex=new int[n];
        for (int i = 0; i < n; i++) {
            ex[i]=gas[i]-cost[i];
            queue.add(new o(ex[i],i));
        }
        Collections.sort( queue, new Comparator<o>() {
            @Override
            public int compare(o o, o t1) {
                if(t1.ex>o.ex){
                    return 1;
                }else{
                    return -1;
                }
            }
        } );
        for (int j = 0; j < queue.size(); j++) {
            o cur=queue.get(j);
            int r=cur.ex;
            int i=(cur.index+1)%n;
            if(r<0){
                return -1;
            }
            while (i!=cur.index){
                r+=ex[i];
                if(r<0){
                    break;
                }
                i=(i+1)%n;
            }
            if(r>=0){
                return cur.index;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] gas={5};
        int[] cost={4};
        System.out.println(new _47().canCompleteCircuit(gas,cost));
    }
}
法二:
public int canCompleteCircuit(int[] gas, int[] cost) {
        int st=gas.length-1;
        int sum=gas[st]-cost[st];
        int ed=0;
        while (ed<st){
            if(sum>=0){
                sum+=gas[ed]-cost[ed++];
            }else{
                sum+=gas[--st]-cost[st];
            }
        }
        return sum>=0?st:-1;
    }
2.valid-palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
“A man, a plan, a canal: Panama”is a palindrome.
“race a car”is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
递归爆栈,只能用迭代。
考虑一下情况,st是字符,ed不是字符,则–ed.
st不是字符,ed是字符,则++st,
st,ed都不是字符,++st,–ed.
st,ed都是字符且相等,++st,ed,否则返回false。

class _50{
    public boolean isPalindrome(String s) {
        int st=0;
        int ed=s.length()-1;
        while (ed>st){
            char stChar=s.charAt(st);
            char edChar=s.charAt(ed);
            if(stChar==edChar||(!Character.isLetterOrDigit(edChar)&&!Character.isLetterOrDigit(stChar))){
                --ed;
                ++st;
            }else if(!Character.isLetterOrDigit(stChar)&&Character.isLetterOrDigit(edChar)){
                ++st;
            }else if(!Character.isLetterOrDigit(edChar)&&Character.isLetterOrDigit(stChar)){
                --ed;
            }else{
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        String s=".,";
        System.out.println(new _50().isPalindrome(s));
    }
}
3.pascals-triangle

Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
可以用二维数组模拟在添加,也可以直接用容器添加。

public class _51 {
    public ArrayList<ArrayList<Integer>> generate(int numRows) {
        if(numRows==0){
            return new ArrayList<ArrayList<Integer>>();
        }
        ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> fir=new ArrayList<Integer>();
        fir.add(1);
        res.add(fir);
        for (int i = 2; i <= numRows; i++) {
            ArrayList<Integer> k=new ArrayList<Integer>();
            k.add(1);
            for (int j = 2; j <= i-1; j++) {
                k.add(res.get(i-2).get(j-2)+res.get(i-2).get(j-1));
            }
            k.add(1);
            res.add(k);
        }
        return res;
    }
    public static void main(String[] args) {
        System.out.println(new _51().generate(0));
    }
}

4.pascals-triangle-ii

Given an index k, return the k th row of the Pascal’s triangle.
For example, given k = 3,
Return[1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
O(k)做法。
杨辉三角,第n行第m个数的值为C(m-1,n-1).
用double来进行乘除运算,会出现精度问题,
所以我们要进行精度控制,若大于等于eps我们则向上取整,若小与我们则向下取整即可。
这道题用long可以直接过,emmm,不需要考虑精度。

一.
public ArrayList<Integer> getRow(int rowIndex) {
        double eps=1e-6;
        ArrayList<Integer> res=new ArrayList<Integer>();
        if(rowIndex==0){
            res.add(1);
            return res;
        }
        rowIndex+=1;
        res.add(1);
        double up;
        double down;
        double re=1;
        for (int i = 2; i <= rowIndex-1; i++) {
            down=i-1;
            up=rowIndex-i+1;
            re=re/down*up;
            if(re-(int)re<eps){ 
                re=Math.floor(re);
            }else{
                re=Math.ceil(re);
            }
            res.add((int) re);
        }
        res.add(1);
        return res;
    }
二:    
public ArrayList<Integer> getRow(int rowIndex) {
        ArrayList<Integer> res=new ArrayList<Integer>();
        if(rowIndex==0){
            res.add(1);
            return res;
        }
        rowIndex+=1;
        res.add(1);
        long up;
        long down;
        long re=1;
        for (int i = 2; i <= rowIndex-1; i++) {
            down=i-1;
            up=rowIndex-i+1;
            re=re*up/down;
            res.add((int) re);
        }
        res.add(1);
        return res;
    }
5.binary-tree-maximum-path-sum

Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/ \
2 3
Return6.

public class _53 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    int max;
    public int maxPathSum(TreeNode root) {
        max=Integer.MIN_VALUE;
        dfs(root);
        return max;
    }
    private int dfs(TreeNode root){
        if(root==null){
            return 0;
        }
        int l=Math.max(dfs(root.left),0); //root的左边谁最大
        int r=Math.max(dfs(root.right),0); //root的左边谁最大
        max=Math.max(max,root.val+l+r); //左右加上还有根
        return Math.max(l,r)+root.val; //返回左右子树哪个的值比较大。
    }
    public static void main(String[] args) {
        TreeNode treeNode=new TreeNode(-2);
        System.out.println(new _53().maxPathSum(treeNode));
    }
}
6.sum-root-to-leaf-numbers

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.
左右子树遍历一遍即可。

public class _54 {
    int sum;
    public int sumNumbers(TreeNode root) {
        if(root==null){
            return 0;
        }
        sum=0;
        dfs(root,0);
        return sum;
    }
    private void dfs(TreeNode root,int res){
        res=res*10+root.val;
        if(root.left==null&&root.right==null){
            sum+=res;
            return;
        }
        if(root.left!=null){
            dfs(root.left,res);
        }
        if(root.right!=null){
            dfs(root.right,res);
        }
    }
    public static void main(String[] args) {
        TreeNode treeNode=new TreeNode(1);
        treeNode.left=new TreeNode(2);
        treeNode.right=new TreeNode(3);
        System.out.println(new _54().sumNumbers(treeNode));
    }
}
7.populating-next-right-pointers-in-each-node

Given a binary tree

struct TreeLinkNode {
  TreeLinkNode *left;
  TreeLinkNode *right;
  TreeLinkNode *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.
Initially, all next pointers are set toNULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

     1
   /  \
  2    3
 / \  / \
4  5  6  7

After calling your function, the tree should look like:

     1 -> NULL
   /  \
  2 -> 3 -> NULL
 / \  / \
4->5->6->7 -> NULL
public class Solution {
    public void connect(TreeLinkNode root) {
        if(root==null){
            return;
        }
        if(root.left!=null&&root.right!=null){
            root.left.next=root.right;
        }
        if(root.right!=null&&root.next!=null){
            root.right.next=root.next.left;
        }
        connect(root.left);
        connect(root.right);
    }
}
点赞