Thursday, September 3, 2020

LeetCode [1197] Minimum Knight Moves

 1197. Minimum Knight Moves

Medium

In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].

A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

Return the minimum number of steps needed to move the knight to the square [x, y].  It is guaranteed the answer exists.

 

Example 1:

Input: x = 2, y = 1
Output: 1
Explanation: [0, 0] → [2, 1]

Example 2:

Input: x = 5, y = 5
Output: 4
Explanation: [0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5]

 

Constraints:

  • |x| + |y| <= 300
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    Map<String, Integer> map = new HashMap<>();
    public int minKnightMoves(int x, int y) {
        x = Math.abs(x);
        y = Math.abs(y);
        if(x+y==0) return 0;
        if(x+y==2) return 2;
        String key = x+":"+y;
     //   System.out.println(key);
        if(!map.containsKey(key)){
            int a = minKnightMoves(x-1, y-2);
            int b = minKnightMoves(x-2, y-1);
            map.put(key, Math.min(a,b)+1);
        }
        return map.get(key);
    }
}

LeetCode [1203] Sort Items by Groups Respecting Dependencies

 1203. Sort Items by Groups Respecting Dependencies

Hard

There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.

Return a sorted list of the items such that:

  • The items that belong to the same group are next to each other in the sorted list.
  • There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).

Return any solution if there is more than one solution and return an empty list if there is no solution.

 

Example 1:

Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
Output: [6,3,4,1,5,2,0,7]

Example 2:

Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
Output: []
Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.

 

Constraints:

  • 1 <= m <= n <= 3*10^4
  • group.length == beforeItems.length == n
  • -1 <= group[i] <= m-1
  • 0 <= beforeItems[i].length <= n-1
  • 0 <= beforeItems[i][j] <= n-1
  • i != beforeItems[i][j]
  • beforeItems[i] does not contain duplicates elements.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
for group i, its previous node is n+2*i, its next node is n+2*i+1
*/
class Solution {
    Map<Integer, Set<Integer>> links = new HashMap<>();
    public int[] sortItems(int n, int m, int[] group, List<List<Integer>> beforeItems) {
        for(int i=0; i<n; ++i){
            if(group[i]!=-1){//n+2*group[i]->i->n+2*group[i]+1
                links.computeIfAbsent(n+2*group[i], k->new HashSet<>()).add(i);
                links.computeIfAbsent(i, k->new HashSet<>()).add(n+2*group[i]+1);
            }
        }
        
        for(int i = 0; i<n; ++i){
            for(int j : beforeItems.get(i)){//j->i
                if(group[i]==group[j]){
                    links.computeIfAbsent(j, k->new HashSet<>()).add(i);
                }else{
                    if(group[j]==-1){//j->n+2*group[i]
                        links.computeIfAbsent(j, k->new HashSet<>()).add(n+2*group[i]);
                    }else if(group[i]==-1){//n+2*group[j]+1->i
                        links.computeIfAbsent(n+2*group[j]+1, k->new HashSet<>()).add(i);
                    }else{//n+2*group[j]+1->n+2*group[i]
                        links.computeIfAbsent(n+2*group[j]+1, k->new HashSet<>()).add(n+2*group[i]);
                    }
                }
            }
        }

        Set<Integer> visited = new HashSet<>();
        Set<Integer> path = new HashSet<>();
        List<Integer> sorted = new ArrayList<>();
        for(int item = n+2*m-1; item>=0; --item){//must call from group bound nodes to push the same group items together
            if(visited.contains(item)) continue;
            path.add(item);
            if(hasCycle(item, visited, path, sorted)) return new int[0];
            path.remove(item);
        }

        int[] ret = new int[n];
        int i = 0;
        for(int item : sorted){
            if(item<n) ret[i++] = item;
        }
        return ret;
    }

    boolean hasCycle(int item, Set<Integer> visited, Set<Integer> path, List<Integer> sorted){
        visited.add(item);
        if(links.containsKey(item)){
            for(int next : links.get(item)){
                if(path.contains(next)) return true;
                if(visited.contains(next)) continue;
                path.add(next);
                if(hasCycle(next, visited, path, sorted)) return true;
                path.remove(next);
            }
        }
        sorted.add(0, item);
        return false;
    }
}

LeetCode [1231] Divide Chocolate

 1231. Divide Chocolate

Hard

You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness.

You want to share the chocolate with your K friends so you start cutting the chocolate bar into K+1 pieces using K cuts, each piece consists of some consecutive chunks.

Being generous, you will eat the piece with the minimum total sweetness and give the other pieces to your friends.

Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally.

 

Example 1:

Input: sweetness = [1,2,3,4,5,6,7,8,9], K = 5
Output: 6
Explanation: You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9]

Example 2:

Input: sweetness = [5,6,7,8,9,1,2,3,4], K = 8
Output: 1
Explanation: There is only one way to cut the bar into 9 pieces.

Example 3:

Input: sweetness = [1,2,2,1,2,2,1,2,2], K = 2
Output: 5
Explanation: You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2]

 

Constraints:

  • 0 <= K < sweetness.length <= 10^4
  • 1 <= sweetness[i] <= 10^5
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
    public int maximizeSweetness(int[] sweetness, int K) {
        long sum = 0;
        for(long s : sweetness) sum += s;
        long l = 1, r = sum;
        while(l<r){
            long mid = l + (long)Math.ceil((r-l)/2.0);
            System.out.println(l + " " + r);
            if(!valid(sweetness, K, mid))
            {
                r = mid-1;
            }else{
                l = mid;
            }
        }
        return (int)l;
    }
    
    //return true if consecutive sweetness >= target when dividing into K+1 subarrays
    boolean valid(int[] sweetness, int K, long target){
        int count = 0;
        long cur = 0;
        for(long s : sweetness)
        {
            if(cur+s<target)
            {
                cur += s;
            }else{
                count++;
                cur = 0;
                if(count>=K+1) return true;
            }
        }
        return false;
    }
}

LeetCode [1283] Find the Smallest Divisor Given a Threshold

 1283. Find the Smallest Divisor Given a Threshold

Medium

Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.

Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).

It is guaranteed that there will be an answer.

 

Example 1:

Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. 
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). 

Example 2:

Input: nums = [2,3,5,7,11], threshold = 11
Output: 3

Example 3:

Input: nums = [19], threshold = 5
Output: 4

 

Constraints:

  • 1 <= nums.length <= 5 * 10^4
  • 1 <= nums[i] <= 10^6
  • nums.length <= threshold <= 10^6
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    public int smallestDivisor(int[] nums, int threshold) {
        int l = 1, r = (int)1e6;
        while(l<r)
        {
            int mid = l + (r-l)/2;
            int sum = 0;
            for(int n:nums){
                sum += Math.ceil(n/(double)mid);
            }
            if(sum>threshold) l = mid+1;
            else r = mid;
        }
        return (int)l;
    }
}

LeetCode [1293] Shortest Path in a Grid with Obstacles Elimination

 1293. Shortest Path in a Grid with Obstacles Elimination

Hard

Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell.

Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m-1, n-1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.

 

Example 1:

Input: 
grid = 
[[0,0,0],
 [1,1,0],
 [0,0,0],
 [0,1,1],
 [0,0,0]], 
k = 1
Output: 6
Explanation: 
The shortest path without eliminating any obstacle is 10. 
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).

 

Example 2:

Input: 
grid = 
[[0,1,1],
 [1,1,1],
 [1,0,0]], 
k = 1
Output: -1
Explanation: 
We need to eliminate at least two obstacles to find such a walk.

 

Constraints:

  • grid.length == m
  • grid[0].length == n
  • 1 <= m, n <= 40
  • 1 <= k <= m*n
  • grid[i][j] == 0 or 1
  • grid[0][0] == grid[m-1][n-1] == 0

Time Complexity
O(m*n*k) time complexity
This is because for every cell (m*n), in the worst case we have to put that cell into the queue/bfs k times.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
    public int shortestPath(int[][] grid, int k) {
        int[][] dirs = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};
        int m = grid.length, n = grid[0].length;
        Queue<int[]> que = new LinkedList<>();//r, c, b
        int[][] blks = new int[m][n];//min blks to get i, j
        for(int i=0; i<m; ++i){
            Arrays.fill(blks[i], Integer.MAX_VALUE);
        }
        blks[0][0] = 0;
        que.add(new int[]{0,0,0});
        int steps = 0;
        
        while(!que.isEmpty()){
            int sz = que.size();
            for(int i=0; i<sz; ++i){
                int[] t = que.poll();
                int r = t[0], c = t[1], b = t[2];
                if(r==m-1 && c==n-1) return steps;
                for(int[] d : dirs){
                    int r1 = r+d[0], c1 = c+d[1], b1 = 0;
                    if(r1>=0 && r1<m && c1>=0 && c1<n){
                        b1 = b + grid[r1][c1];
                        //blks[m-1][n-1] must be <= k when we reach it && only push [r1][c1] if its blks value decreased
                        if(b1>k || b1>=blks[r1][c1]) continue;
                        blks[r1][c1] = b1;  
                        que.add(new int[] {r1, c1, b1});
                    }
                }
            }
            steps++;
        }
        return -1;
    }
}

一、输入一二维数组,0是路1是墙,从左上到右下的最少走多少步

follow up,如果能够把一堵墙拆掉,那么从左上到右下最少走多少步