lintcode做题总结, Sept 18

1. Number of 1 Bits My Submissions Question Solution 

这道题本来很简单的,但是在测试中参数int的值会越界,我也不知道是怎么穿进去的

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        for(int i=1; i<33; i++){
            if(((n>>i) & (1)) != 0){
                count++;
            }
        }
        return count;
    }

}

2. House Robber 这道题用的是一维DP

public class Solution {
    public int rob(int[] num) {
        if(num==null || num.length==0)
            return 0;
 
        int n = num.length;
     
        int[] dp = new int[n+1];
        dp[0]=0;
        dp[1]=num[0];
     
        for (int i=2; i<n+1; i++){
           dp[i] = Math.max(dp[i-1], dp[i-2]+num[i-1]);
        }
     
        return dp[n];
    }
}


3. Happy Number 这道题好没意思,就是简单的计算

public class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> set = new HashSet<Integer>();
        while(!set.contains(n)){
            set.add(n);
            n = sum(getDigits(n));
            if (n == 1)
                return true;
        }
        return false;
    }
    public int sum(int[] arr){
        int sum = 0;
        for(int i: arr){
            sum = sum + i*i;
        }
        return sum;
    }
 
    public int[] getDigits(int n){
        String s = String.valueOf(n);
        int[] result = new int[s.length()];
        int i=0;
        while(n>0){
            int m = n%10;
            result[i++] = m;
            n = n/10;
        }
        return result;
    }
}

4. Remove Linked List Elements 链表删除元素

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode helper = new ListNode(0);
        helper.next = head;
        ListNode p = helper;
     
        while(p.next != null){
            if(p.next.val == val){
                ListNode next = p.next;
                p.next = next.next; 
            }else{
                p = p.next;
            }
        }
     
        return helper.next;
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值