Java —— Leetcode Easy problem #2 (easy in 21-50 )

21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

My Solution:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode newHead = new ListNode(0);
        ListNode p = l1, q = l2, res = newHead;
        if(p == null) return q;
        if(q == null) return p;
        while(p != null && q != null) {
            if(p.val > q.val) {
                res.next = new ListNode(q.val);
                res = res.next;
                q = q.next;
            } else {
                res.next = new ListNode(p.val);
                res = res.next;
                p = p.next;
            }  
        }
        if (p == null) {
            while(q != null) {
                res.next = new ListNode(q.val);
                res = res.next;
                q = q.next;
            }
        }
        if (q == null) {
            while(p != null) {
                res.next = new ListNode(p.val);
                res = res.next;
                p = p.next;
            }
        }
        return newHead.next;
    }
}

Runtime: 1 ms, faster than 31.56% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 39.5 MB, less than 14.93% of Java online submissions for Merge Two Sorted Lists.

It’s a simple problem with very easy algorithm. But as a rookie I have little idea about what ListNode is… so my solution looks suck, at least from this report…

Other Solution

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummy = new ListNode(0);
        ListNode l3 = dummy;
        while (l1 != null && l2 != null){
            if (l1.val <= l2.val){
                l3.next = l1;
                l1 = l1.next;
            }else{
                l3.next = l2;
                l2 = l2.next;
            }
            l3 = l3.next;
        }
        if (l1 != null) l3.next = l1;
        if (l2 != null) l3.next = l2;
        return dummy.next;
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 39.5 MB, less than 15.03% of Java online submissions for Merge Two Sorted Lists.

Compared with my solution, this solution have same algorithm with mine but the code of ListNode are more concise.

26. Remove Duplicates from Sorted Array

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

 // nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

Solution:

class Solution {
    public int removeDuplicates(int[] nums) {
        int point = 0;
        for (int i = 0, len = nums.length; i<len - 1; i++) {
            if (nums[i] != nums[i+1]) point++;
            nums[point] = nums[i+1];
        }
        
        return point + 1;
    }
}

Runtime: 1 ms, faster than 98.38% of Java online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 40.3 MB, less than 81.38% of Java online submissions for Remove Duplicates from Sorted Array.

Honestly, I hadn’t understand this problems until I viewed the comments… Here is the solution from a netizen (who is bald so he must be very talent ?).

Official Solution

public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}

27. Remove Element

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

My Solution

class Solution {
    public int removeElement(int[] nums, int val) {
        int point = 0;
        if(nums.length == 0 || (nums.length == 1 && nums[0] == val) ) {
            return point;
        }
        for(int j = 0; j < nums.length; j++) {
            if (nums[j] == val) {
                int i = j+1; 
                if(i >= nums.length) {
                       return point; 
                    }
                while(nums[i] == val) {
                    if(i == nums.length-1) {
                       return point; 
                    }
                    i++;
                }
                nums[j] = nums[i];
                nums[i] = val;
            }
            point++;
        }
        return point;
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Element.
Memory Usage: 36.1 MB, less than 100.00% of Java online submissions for Remove Element.

Honestly, as a rookie, I’m not good at solving such problem in some restriction. Though the report looks good but I think my code is too complicated and it could be more simplified. And there is only O(1) extra memory can be used but I used O(2).

Official Solution

public int removeElement(int[] nums, int val) {
    int i = 0;
    for (int j = 0; j < nums.length; j++) {
        if (nums[j] != val) {
            nums[i] = nums[j];
            i++;
        }
    }
    return i;
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Element.
Memory Usage: 36.1 MB, less than 100.00% of Java online submissions for Remove Element.

I’ve gotta say it’s perfect. My approach is to swap the positions of the numbers and put all the numbers equal to Val at the end of the array. This approach undoubtedly requires more judgment conditions. The official solution only considers the output and uses fewer statements to get the desired result.

28. Implement strStr()

Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().


My Solution

class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack.equals("") && needle.equals("")) return 0;
        return haystack.indexOf(needle);  
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Implement strStr().
Memory Usage: 37.3 MB, less than 94.10% of Java online submissions for Implement strStr().

I don’t know whether I can use indexOf()… But as you can see it would be pretty easy with indexOf().

Other Solution

public int strStr(String haystack, String needle) {
        if (needle.length() == 0) {
            return 0;
        } else if (haystack.length() == 0) {
            return -1;
        }
		
        if (haystack.contains(needle)) {
            for (int i = 0; i < haystack.length(); i++) {
                if (haystack.substring(i, needle.length()+i).equals(needle)) {
                    return i;
                }
            }
        }
        return -1;
    }

Runtime: 0 ms, faster than 100.00% of Java online submissions for Implement strStr().
Memory Usage: 37.2 MB, less than 97.85% of Java online submissions for Implement strStr().

It’s a solution without indexOf(). It uses substring to achieve the function.

35. Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

My Solution

public int searchInsert(int[] nums, int target) {
        if(nums.length == 0) return 0;
        int a = 0;
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == target) return i;
            if(nums[i] < target) a++;
        }
        return a;
    }

Runtime: 0 ms, faster than 100.00% of Java online submissions for Search Insert Position.
Memory Usage: 38.1 MB, less than 98.76% of Java online submissions for Search Insert Position.

It’s kind of easy problems.

Other solution

public int searchInsert(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        while (l <= r){
            int mid = (r + l) / 2;
            if (nums[mid] == target) return mid;
            if (nums[mid] > target) r = mid - 1;
            else l = mid + 1;
        }
        return l; 
    }

100% faster java Solutions, 98.89% faster memory

38. Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221

1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.

Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

My Solution

public String countAndSay(int n) {
        String res = "1";
        for (int i = 0; i < n-1; i++) {
            int count = 1;
            String a = res.substring(0,1);
            String b = "";
            for(int j = 1; j < res.length(); j++){
                if(res.substring(j,j+1).equals(a)) {
                    count++;   
                } else {
                    b += String.valueOf(count) + a;
                    count = 1;
                    a = res.substring(j, j+1);
                }
            }
            res = b + String.valueOf(count) + a;   
        }
        return res;
    }

Runtime: 8 ms, faster than 14.43% of Java online submissions for Count and Say.
Memory Usage: 36.2 MB, less than 48.44% of Java online submissions for Count and Say.

Other Solution

public String countAndSay(int n) {
        String str = "1";
        for(int i=2; i<=n; i++){
            StringBuilder temp = new StringBuilder();
            int counter = 1;
            char prev = str.charAt(0);
            for(int j=1; j<str.length(); j++){
                char ch = str.charAt(j);
                if(prev != ch){
                    temp.append(counter);
                    temp.append(prev);
                    counter = 1;
                    prev = ch;
                }
                else{
                    counter++;
                }
            }
            temp.append(counter);
            temp.append(prev);
            str = temp.toString();
        }
        return str;
    }

Runtime: 1 ms, faster than 98.91% of Java online submissions for Count and Say.
Memory Usage: 34 MB, less than 100.00% of Java online submissions for Count and Say.

This solution’s algorithm is alomst same with mine but he has a better code.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值