[leetCode刷题笔记]2017.02.13

74. Search a 2D Matrix

本来准备用二分法做的,后来看了网上。觉得这种方法不错。先看比较每一排的最后一个元素,如果target大于它,则要往前进一个排,如果小于它,则要横着减去一位时间复杂度:O(m+n)

public class Solution {

    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int i = 0;
        // last node of the row
        int j = matrix[0].length - 1;
        
        while (i < matrix.length && j >= 0) {
            int x = matrix[i][j];
            if (target == x) {
                return true;
            }
            if (target < x) {
                j--;
            }
            else {
                i++;
            }
        }
        return false;
    }

}

75. Sort Colors

这道题看了网上的神做法,平移插入。。。O(n)

就是存储3个index对应三种颜色,根据循环得到nums[i]的值,将三种颜色进行平移。2跑的最快,所有碰到所有值都会移动,1只有小于二才会移动,0只有小于1才会移动

http://blog.csdn.net/github_34514750/article/details/52432086


78. Subsets

用递归做,取res中现有list,每个list都加新的元素nums[i]然后再放回res中,同时保留原有list. 从[]开始一次加一个新元素。

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new LinkedList<>();
        List<Integer> tmpList = new LinkedList<>();


        Arrays.sort(nums);
        solve(res, nums, tmpList, 0);


        return res;
    }
    
    private void solve(List<List<Integer>> res, int[] nums, List<Integer> temList, int index) {
        if (index == nums.length) {
            res.add(new LinkedList(temList));
            return;
        }
        solve(res, nums, temList, index + 1);
        temList.add(nums[index]);
        solve(res,nums,temList,index+1);
        temList.remove(temList.size()-1);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值