Tag Archives: java

Syntax error, syntax expected name

It means grammatical error;

Carefully check the code you write. If you are creating entity class, see if it is missing; if you are creating method, check the position of () and {}.

They are all small problems, which can be found by careful examination.

LeetCode 23. Merge k Sorted Lists(java)

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Solution 1: use heap to do it. First, put the first element of K lists into heap. After each poll, put it into the next element of the poll until the heap is empty. The time complexity is O (mklogk), and the space complexity is O (k)

public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        if (lists.length == 1) return lists[0];
        PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });
        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) queue.add(lists[i]);
        }
        ListNode dummy = new ListNode(-1), cur = dummy;
        while (!queue.isEmpty()) {
            ListNode temp = queue.poll();
            cur.next = temp;
            cur = temp;
            if (temp.next != null) queue.add(temp.next);
        }
        return dummy.next;
    }

Solution 2: the idea of merge sort is better than solution 1. List merges in pairs each time, until the merges into a list, the time complexity is O ((M / 2) (K / 2 + K / 4 + K / 8 +…) )It is O (kmlogk), but it has a constant number of optimizations than method one. The space complexity is O (1)

public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        int begin = 0, end = lists.length - 1;
        while (begin < end) {
            int mid = (begin + end - 1) / 2;
            for (int i = 0; i <= mid; i++) {
                lists[i] = merge2list(lists[i], lists[end - i]);
            }
            end = (begin + end) / 2;
        }
        return lists[0];
    }
    public ListNode merge2list(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) return null;
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummy = new ListNode(-1), cur = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                cur = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                cur = l2;
                l2 = l2.next;
            }
        }
        if (l1 != null) cur.next = l1;
        if (l2 != null) cur.next = l2;
        return dummy.next;
    }

Servlet error: no interface expected here

No interface expected here error was encountered when implementing the code. Idea was not compiled. No interface expected here means there is no interface.

resolvent

After a look around, we found that servlet is an interface, not a class. Httpservlet is an abstract class, so when we change it to servlet, we need to change extensions to implements.

Change extend to implements

 

 

 

LeetCode 332. Reconstruct Itinerary

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
idea:
we have a list of edges, each node pair represents for [from, to]. and that are the series of tickets
and we know that the journel starts with JFK, we need to resort it and return with the nodes in order.
example:
Input: [[“JFK”,“SFO”],[“JFK”,“ATL”],[“SFO”,“ATL”],[“ATL”,“JFK”],[“ATL”,“SFO”]]
Output: [“JFK”,“ATL”,“JFK”,“SFO”,“ATL”,“SFO”]
Explanation: Another possible reconstruction is [“JFK”,“SFO”,“ATL”,“JFK”,“ATL”,“SFO”].
But it is larger in lexical order.
there are four instructions:
1 If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary [“JFK”, “LGA”] has a smaller lexical order than [“JFK”, “LGB”].
2 All airports are represented by three capital letters (IATA code).
3 You may assume all tickets form at least one valid itinerary.
4 One must use all the tickets once and only once.

public List<String> findItinerary(List<List<String>> tickets)

I’m still trying to solve this using BFS, each time I only choose one neighbor to go, the one with smallest lexi order. so it’s bascally dfs but I’m too lazy to even think about how to write this in dfs.
but sadly, it’s MLE

class Solution {
    public List<String> findItinerary(List<List<String>> tickets) {
        HashMap<String, List<String>> map = new HashMap<>();
        
        for (List<String> ticket: tickets) {
            map.computeIfAbsent(ticket.get(0), k -> new ArrayList<>());
            map.get(ticket.get(0)).add(ticket.get(1));
        }
        // we will using bfs but each time we only go with negihbor with minimum lexi, although for situations like this, it's better for us to implement dfs instead of bfs
        Queue<String> queue = new LinkedList<>();
        queue.offer("JFK");
        List<String> res = new ArrayList<>();
        res.add("JFK");
        //i don;t think visited will be useful, because we might revisited previous node, like we might need to return the JFK again in example
        while (!queue.isEmpty()) {
            String cur = queue.poll();
            if (!map.containsKey(cur)) { //we neeed to check if map contains this key in case it is the last one
                break;
            }
            int size = map.get(cur).size();
            String min = "ZZZ";
            for (int i = 0; i < size; i++) {
                if (map.get(cur).get(i).compareTo(min) < 0) {
                    min = map.get(cur).get(i);
                }
            }
            queue.offer(min);
            res.add(min);
        }
        return res;
    }
}

So we using DFS:
/ / why can DFS guarantee to travel all the edges and only once?

class Solution {
    public List<String> findItinerary(List<List<String>> tickets) {
        HashMap<String, PriorityQueue<String>> map = new HashMap<>();
        
        for (List<String> ticket: tickets) {
            map.computeIfAbsent(ticket.get(0), k -> new PriorityQueue<>()).add(ticket.get(1));
        }
        List<String> route = new LinkedList<>();
        dfs(map, route, "JFK"); 
        return route;
    }
    
    private void dfs(HashMap<String, PriorityQueue<String>> map, List<String> route, String node) {
        while (map.containsKey(node) && !map.get(node).isEmpty()) { //if we can move forward 
            dfs(map, route, map.get(node).poll());
        }
        route.add(0, node); //alwatys added to the head of this route list
    }
}

Of course, we can write DFs in an iterative way

public List<String> findItinerary(String[][] tickets) {
    Map<String, PriorityQueue<String>> targets = new HashMap<>();
    for (String[] ticket : tickets)
        targets.computeIfAbsent(ticket[0], k -> new PriorityQueue()).add(ticket[1]);
    List<String> route = new LinkedList();
    Stack<String> stack = new Stack<>();
    stack.push("JFK");
    while (!stack.empty()) {
        while (targets.containsKey(stack.peek()) && !targets.get(stack.peek()).isEmpty())
            stack.push(targets.get(stack.peek()).poll());
        route.add(0, stack.pop());
    }
    return route;
}

Jstack command execution error: unable to open socket file: target process not responding or hotspot VM not loaded

An error is reported when the jstack command is executed. The error is as follows

Unable to open socket file: target process not responding or HotSpot VM not loaded
The -F option can be used when the target process is not responding

This process can be viewed through PS command

I found an article about jstack command not configured well on the Internet

Switch to the / tmp directory

cd /tmp

There are several directories at the beginning of hsperfdata. Go to the directory to see if there is a process number executed by jstack

After checking, it is found that the process behind jstack is not executed by the root user, and the switch to another user is successful

Later, we found that PS – aux can also see who executed the process, so we don’t have to be so troublesome

[Two Sigma OA] Longest Chain

Title:

http://www.1point3acres.com/bbs/thread-131978-1-1.html

realization:

import java.util.*;

/**
 * Created by Min on 10/2/2017.
 */
public class LongestChain {
    private int getLongestChain(String[] words) {
        Map<Integer, Set<String>> map = new HashMap<Integer, Set<String>>();
        for (String word : words) {
            Set<String> set = map.get(word.length());
            if (set == null) {
                set = new HashSet<String>();
                map.put(word.length(), set);
            }
            set.add(word);
        }
        int ans = 0;
        List<Integer> lengthList = new ArrayList<Integer>(map.keySet());
        Collections.sort(lengthList, Collections.reverseOrder());
        return helper(0, lengthList, map, "");
    }
    private int helper(int start, List<Integer> list, Map<Integer, Set<String>> map, String prev) {
        if (start == list.size()) {
            return 0;
        }
        int ans = 0;
        if (start == 0) {
            for (String word : map.get(list.get(0))) {
                ans = Math.max(ans, helper(start + 1, list, map, word) + 1);
            }
        } else if (prev.length() -1 == list.get(start)) {
            Set<String> wordSet = map.get(list.get(start));
            for (int i = 0; i < prev.length(); i++) {
                String newWord = prev.substring(0, i) + prev.substring(i + 1);
                if (wordSet.contains(newWord)) {
                    wordSet.remove(newWord);
                    ans = Math.max(ans, helper(start + 1, list, map, newWord) + 1);
                }
            }
        }
        return ans;
    }
    public static void main(String[] args) {
        String[] input = {"a","ba","bca","bda","bdca"};
        LongestChain solution = new LongestChain();
        System.out.println(solution.getLongestChain(input));
    }

}

[UNK]

import java.util.*;

/**
 * Created by Min on 10/2/2017.
 */
public class LongestChain2 {
    public int getLongestChain(String[] words) {
        Set<String> set = new HashSet<String>();
        for (String word : words) {
            set.add(word);
        }
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        int ans = 0;
        for (String word : words) {
            Integer length =map.get(word);
            if (length == null) {
                length = dfs(word, map, set);
            }
            ans = Math.max(ans, length);
        }
        return ans;
    }

    private int dfs(String word, Map<String, Integer> map, Set<String> set) {
        Integer ans = map.get(word);
        if (ans != null) {
            return ans.intValue();
        }
        ans = 0;
        for (int i = 0; i < word.length(); i++) {
            String newWord = word.substring(0, i) + word.substring(i + 1);
            ans = Math.max(ans, dfs(newWord, map, set) + 1);
        }
        map.put(word, ans);
        return ans.intValue();
    }
    public static void main(String[] args) {
        String[] input = {"a","ba","bca","bda","bdca"};
        LongestChain2 solution = new LongestChain2();
        System.out.println(solution.getLongestChain(input));
    }
}

 

Reproduced in: https://www.cnblogs.com/Gryffin/p/7623249.html

Mybatis idea environment integration jar package

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.4</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
    </dependencies>

Can read JBIG2 image: JBIG2 imageio is not installed

1、 Problem description

Error information: org.apache.pdfbox . contentstream.PDFStreamEngine.operatorException ( PDFStreamEngine.java:917 ) – Cannot read JBIG2 image: jbig2-imageio is not installed

Relevant environmental information:

An error occurred when calling the renderimagewithdpi (int PageIndex, float DPI) method of pdfrenderer

Pdfrenderer uses pdfbox, POM coordinates are:

<dependency>
	<groupId>org.apache.pdfbox</groupId>
	<artifactId>pdfbox</artifactId>
	<version>2.0.19</version>
</dependency>

2、 Solutions

Add the following POM dependencies

<dependency>
	<groupId>org.apache.pdfbox</groupId>
	<artifactId>jbig2-imageio</artifactId>
	<version>3.0.2</version>
</dependency>

 

Reference link:

https://blog.csdn.net/chengzuo875963/article/details/100913781 (this link has been used for reference, but it didn’t work after trying. Finally, we found the scheme of the following link through Google.)

https://github.com/levigo/jbig2-imageio/issues/54

Android “handler” is abstract; can’t be identified solution

Today, when I use Android’s own refresh control, I need a handler for instance calls, but I report an error in my own instance calls
“handler” is abstract; can’t be identified
because there is an error in my import library. I use Android’s handler library instead of Java’s handle library
the solution is as follows
use “import” to import android.os.Handler ; ”Replace “import” java.util.logging .Handler;”

This can be solved, in addition to the reference to this blog