力扣---2020.8.3

415. 字符串相加

字符串加法、链表加法以及二进制加法之类的都可以这么写

class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder(); //可以换用stack,list等存储
        int len1 = num1.length()-1,len2 = num2.length()-1;
        int carry = 0;
        while(len1 >= 0 || len2 >= 0 || carry > 0){
            if(len1 >= 0)  carry += num1.charAt(len1--) - '0';
            if(len2 >= 0)  carry += num2.charAt(len2--) - '0';
            sb.append(carry%10);
            carry /= 10;
        }
        return sb.reverse().toString();
    }
}

剑指 Offer 56 - II. 数组中数字出现的次数 II

class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int num : nums){
            map.put(num,map.getOrDefault(num,0)+1);
        }

        for(int num : nums){
            if(map.get(num)==1){
                return num;
            }
        }
        return -1;
    }
}
class Solution {
    public int singleNumber(int[] nums) {
        int a = 0;
        int b = 0;
        for(int num : nums) {
        	a = (a ^ num) & ~b;
        	b = (b ^ num) & ~a;
        }
        return a;
    }
}
class Solution {
    public int singleNumber(int[] nums) {
        int[] counts = new int[32];
        for(int num : nums) {
            for(int j = 0; j < 32; j++) {
                counts[j] += num & 1;
                num >>>= 1;
            }
        }
        int res = 0, m = 3;
        for(int i = 0; i < 32; i++) {
            res <<= 1;
            res |= counts[31 - i] % m;
        }
        return res;
    }
}

剑指 Offer 24. 反转链表

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null){
            return head;
        }
        ListNode prev = null;
        ListNode curr = head;
        while(curr!=null){
            ListNode nextTmp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTmp;
        }
        return prev;
    }
}
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode nextTmp = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return nextTmp; 
    }
}

你知道的越多,你不知道的越多。

相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页