第22天--算法(Leetcode 53,56,62)

53.最大子数组和

public int maxSubArray(int[] nums) {
        int res = Integer.MIN_VALUE;
        int curRes = 0;
        if(nums == null || nums.length == 0) {
            return 0;
        }
        for(int i = 0;i < nums.length;i ++) {
            curRes += nums[i];
            res = Math.max(curRes,res);
            curRes = curRes < 0 ? 0 : curRes;
        }
        return res;
    }
56.合并区间
class Info {
        int start;
        int end;
        public Info(int start,int end) {
            this.start = start;
            this.end = end;
        }
    }
    class InfoComparator implements Comparator<Info> {
        @Override
        public int compare(Info o1, Info o2) {
            return o1.start - o2.start;
        }
    }
    public int[][] merge(int[][] intervals) {
        if(intervals == null || intervals.length == 0) {
            return new int[0][0];
        }
        Info temp[] = new Info[intervals.length];
        for(int i = 0;i < intervals.length;i ++) {
            temp[i] = new Info(intervals[i][0],intervals[i][1]);
        }
        Arrays.sort(temp,new InfoComparator());
        ArrayList<Info> res = new ArrayList<>();
        int s = temp[0].start;
        int e = temp[0].end;
        for(int i = 1;i < temp.length;i ++) {
            if(temp[i].start > e) {
                res.add(new Info(s,e));
                s = temp[i].start;
                e = temp[i].end;
            }else {
                e = Math.max(e,temp[i].end);
            }
        }
        res.add(new Info(s,e));
        return swap(res);
    }
    public int[][] swap(ArrayList<Info> res) {
        int ans[][] = new int[res.size()][2];
        for(int i = 0;i < res.size();i ++) {
            ans[i][0] = res.get(i).start;
            ans[i][1] = res.get(i).end;
        }
        return ans;
    }

62.不同路径

public int uniquePaths(int m, int n) {
        int x = m + n - 2;
        int y = n - 1;
        long o1 = 1;
        long o2 = 1;
        for(int i = m,j = 1;i <= x && j <= n - 1;i ++,j ++) {
            o1 *= i;
            o2 *= j;
            long temp = gcd(o1,o2);
            o1 /= temp;
            o2 /= temp;
        }
        return (int)o1;
    }
    public long gcd(long x,long y) {
        return y == 0 ? x : gcd(y,x % y);
    }
posted @ 2022-01-17 17:00  现在开始努力  阅读(29)  评论(0)    收藏  举报