LeetCode 67,69,83,88,100

版权声明:本文原创,转载请注明出处:http://blog.csdn.net/zhoumushui https://blog.csdn.net/zhoumushui/article/details/79917074

67. Add Binary

Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".

解法

二进制相加,我的解法比较复杂,应该可以化简为繁。

class Solution {
    public String addBinary(String a, String b) {
        int aLength = a.trim().length();
        int bLength = b.trim().length();
        if (aLength == 0 && bLength == 0) return "0";
        if (aLength == 0) return b;
        if (bLength == 0) return a;
        if (aLength < 10 && bLength < 10)
            return Integer.toBinaryString(Integer.valueOf(a, 2) + Integer.valueOf(b, 2));

        char[] maxChars, minChars;
        int maxLength = 0, minLength = 0;
        if (aLength >= bLength) {
            maxLength = aLength;
            minLength = bLength;
            maxChars = a.toCharArray();
            minChars = b.toCharArray();
        } else {
            maxLength = bLength;
            minLength = aLength;
            maxChars = b.toCharArray();
            minChars = a.toCharArray();
        }
        boolean plusOne = false;
        for (int i = 0; i < minLength; i++) {
            if (minChars[minLength - 1 - i] == '0' && maxChars[maxLength - 1 - i] == '0') {
                maxChars[maxLength - 1 - i] = plusOne ? '1' : '0';
                plusOne = false;
            } else if ((minChars[minLength - 1 - i] == '0' && maxChars[maxLength - 1 - i] == '1')
                    || (minChars[minLength - 1 - i] == '1' && maxChars[maxLength - 1 - i] == '0')) {
                maxChars[maxLength - 1 - i] = plusOne ? '0' : '1';
            } else {
                maxChars[maxLength - 1 - i] = plusOne ? '1' : '0';
                plusOne = true;
            }
        }
        if (plusOne) {
            if (maxLength == minLength) {
                return "1" + new String(maxChars);
            } else {
                for (int i = 0; i < maxLength - minLength; i++) {
                    int index = maxLength - minLength - 1 - i;
                    if (index > 0) {
                        if (maxChars[index] == '0') {
                            maxChars[index] = plusOne ? '1' : '0';
                            plusOne = false;
                        } else if (maxChars[index] == '1') {
                            maxChars[index] = plusOne ? '0' : '1';
                        }
                    } else {
                        if (plusOne) {
                            if (maxChars[0] == '0') {
                                maxChars[0] = '1';
                            } else {
                                maxChars[0] = '0';
                                return "1" + new String(maxChars);
                            }
                        }
                    }
                }
            }
        }
        return new String(maxChars);
    }
}

69. Sqrt(x)

求平方根,我最初用的笨方法时间复杂度非常高,超时了:

// Time Limit Exceeded:
class Solution {
    public int mySqrt(int x) {
        if (x == 0) return 0;
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            int product = i * i;
            if (product == x) {
                return i;
            } else if (product > x) {
                return i - 1;
            }
        }
        return 0;
    }
}

后面考虑到循环参数i的起始值,比如2147483647这个测试用例:
一个循环,每次除以100,直到结果21小于100.
一共除了4次,然后起始值是10的4次方:10000.
然后结果21再去求平方根:4²=16 < 21 < 5²=25,这里取4
所以将10000*4=40000作为起始值,优化后仍然超时。
P.s:
如果21的平方根取4.5呢?或者精确求出sqrt(21)的数值4.58,那么45800和结果46340差距只有540,会不超时吗?

最后在讨论界面看到这个答案:
它的核心是r = (r + x / r) / 2 ,而不是r--

// Accepted
class Solution {
    public int mySqrt(int x) {
        long r = x;
        while (r * r > x)
            r = (r + x / r) / 2;
        return (int) r;
    }
}

83. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

解法

使用递归法:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (null == head || null == head.next) return head;
        head.next = deleteDuplicates(head.next);
        return head.next.val == head.val ? head.next : head;
    }
}

88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

解法

我觉得这题目出得不是太好,nums1的长度输入的时候是m,然后Note里面又说nums1的长度大于等于m+n,足够放下nums1和nums2的数据。不过这样的条件让题目简单了。
直接把nums2的数据放到nums1后面,然后排序就好了:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
       for(int i = 0; i < n; i++)
            nums1[m + i] = nums2[i];
        for (int i = 0; i < m + n; i++) {
            for (int j = i + 1; j < m + n; j++) {
                if(nums1[i]>nums1[j]){
                    int temp = nums1[i];
                    nums1[i] = nums1[j];
                    nums1[j] = temp;
                }
            }
        }
    }
}

上面的解决方案我用了冒泡排序,可以用Array.sort快速排序一行取而代之:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        for(int i = 0; i < n; i++)
            nums1[m + i] = nums2[i];
        Arrays.sort(nums1);
    }
}

100. Same Tree

Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

解法

判断二叉树是否相等,这个题目比较简单,用递归即可:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p == null || q == null) {
            return false;
        } else {
            return (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }
    }
}

简化下代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        if (p == null || q == null) return false;
        return (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页