Thursday, September 3, 2020

LeetCode [1313] Decompress Run-Length Encoded List

 1313. Decompress Run-Length Encoded List

Easy

We are given a list nums of integers representing a list compressed with run-length encoding.

Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.

Return the decompressed list.

 

Example 1:

Input: nums = [1,2,3,4]
Output: [2,4,4,4]
Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].
The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].
At the end the concatenation [2] + [4,4,4] is [2,4,4,4].

Example 2:

Input: nums = [1,1,2,3]
Output: [1,3,3]

 

Constraints:

  • 2 <= nums.length <= 100
  • nums.length % 2 == 0
  • 1 <= nums[i] <= 100
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    public int[] decompressRLElist(int[] nums) {
        List<Integer> ret = new ArrayList<>();
        for(int i=0; i<nums.length; i += 2)
        {
            for(int j=0; j<nums[i]; ++j)
            {
                ret.add(nums[i+1]);
            }
        }
        return ret.stream().mapToInt(i->i).toArray();
    }
}

LeetCode [1334] Find the City With the Smallest Number of Neighbors at a Threshold Distance

 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance

Medium

There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.

Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.

Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.

 

Example 1:

Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Output: 3
Explanation: The figure above describes the graph. 
The neighboring cities at a distanceThreshold = 4 for each city are:
City 0 -> [City 1, City 2] 
City 1 -> [City 0, City 2, City 3] 
City 2 -> [City 0, City 1, City 3] 
City 3 -> [City 1, City 2] 
Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.

Example 2:

Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
Output: 0
Explanation: The figure above describes the graph. 
The neighboring cities at a distanceThreshold = 2 for each city are:
City 0 -> [City 1] 
City 1 -> [City 0, City 4] 
City 2 -> [City 3, City 4] 
City 3 -> [City 2, City 4]
City 4 -> [City 1, City 2, City 3] 
The city 0 has 1 neighboring city at a distanceThreshold = 2.

 

Constraints:

  • 2 <= n <= 100
  • 1 <= edges.length <= n * (n - 1) / 2
  • edges[i].length == 3
  • 0 <= fromi < toi < n
  • 1 <= weighti, distanceThreshold <= 10^4
  • All pairs (fromi, toi) are distinct.
 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
class Solution {
public int findTheCity(int n, int[][] edges, int distanceThreshold) {
        int dis[][] = new int[n][n];
        
        for(int i=0; i<n; ++i){
            for(int j=0; j<n; ++j){
                if(i!=j){
                    dis[i][j] = 1000000;
                }
            }
        }

        for(int[] e : edges){
            dis[e[0]][e[1]] = e[2];
            dis[e[1]][e[0]] = e[2];
        }

        for(int k=0; k<n; ++k){
            for(int i=0; i<n; ++i){
                for(int j=0; j<n; ++j){
                    dis[i][j] = Math.min(dis[i][j], dis[i][k]+dis[k][j]);
                }
            }
        }

        int ret = -1;
        int smallNum = n;
        for(int i=0; i<n; ++i){
            int count = 0;
            for(int j=0; j<n; ++j){
      //          System.out.println(i+" " +j+" "+dis[i][j]);
                if(dis[i][j]<=distanceThreshold){
                    count++;
                }
            }
            if(count<=smallNum){
    //            System.out.println(i + " [" + count + "]" + " small=" + smallNum + " ret=" + ret);
                smallNum = count;
                ret = i;
            }
        }
        return ret;
    }
}

LeetCode [1342] Number of Steps to Reduce a Number to Zero

 1342. Number of Steps to Reduce a Number to Zero

Easy

Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

 

Example 1:

Input: num = 14
Output: 6
Explanation: 
Step 1) 14 is even; divide by 2 and obtain 7. 
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3. 
Step 4) 3 is odd; subtract 1 and obtain 2. 
Step 5) 2 is even; divide by 2 and obtain 1. 
Step 6) 1 is odd; subtract 1 and obtain 0.

Example 2:

Input: num = 8
Output: 4
Explanation: 
Step 1) 8 is even; divide by 2 and obtain 4. 
Step 2) 4 is even; divide by 2 and obtain 2. 
Step 3) 2 is even; divide by 2 and obtain 1. 
Step 4) 1 is odd; subtract 1 and obtain 0.

Example 3:

Input: num = 123
Output: 12

 

Constraints:

  • 0 <= num <= 10^6
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/*
For the binary representation from right to left(until we find the leftmost 1):
if we meet 0, result += 1 because we are doing divide;
if we meet 1, result += 2 because we first do "-1" then do a divide;
ony exception is the leftmost 1, we just do a "-1" and it becomse 0 already.
*/

class Solution {
    public int numberOfSteps (int num) {
        int r = 0;
        if(num==0) return r;
        while(num>0){
            r += (num&1)==1?2:1;
            num >>= 1;
        }
        return r-1;
    }
}

题是说给定n,和三种操作+1,-1,/2,多少步能reduce到0。follow up是分析复杂度,然后如何改进(答的加记忆化)

LeetCode [1368] Minimum Cost to Make at Least One Valid Path in a Grid

 1368. Minimum Cost to Make at Least One Valid Path in a Grid

Hard
Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:
  • 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
  • 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])
  • 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])
  • 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])

Notice that there could be some invalid signs on the cells of the grid which points outside the grid.

You will initially start at the upper left cell (0,0). A valid path in the grid is a path which starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path doesn't have to be the shortest.

You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.

Return the minimum cost to make the grid have at least one valid path.

 

Example 1:

Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
Output: 3
Explanation: You will start at point (0, 0).
The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
The total cost = 3.

Example 2:

Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
Output: 0
Explanation: You can follow the path from (0, 0) to (2, 2).

Example 3:

Input: grid = [[1,2],[4,3]]
Output: 1

Example 4:

Input: grid = [[2,2,2],[2,2,2]]
Output: 3

Example 5:

Input: grid = [[4]]
Output: 0

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 100
 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 {
    int m, n;
    Queue<int[]> bfs = new LinkedList<>();
    int[][] DIR = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
    int[][] dp;
    public int minCost(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        dp = new int[m][n];
        for(int i=0; i<m; ++i){
            Arrays.fill(dp[i], -1);
        }
        int cost = 0;
        dfs(grid, 0, 0, cost);
        while(!bfs.isEmpty()){
            int sz = bfs.size();
            cost++;
            for(int i=0; i<sz; ++i){
                int[] t = bfs.poll();
                for(int[] d:DIR){
                    dfs(grid, t[0]+d[0], t[1]+d[1], cost);
                }
            }
        }
        return dp[m-1][n-1];
    }

    void dfs(int[][] grid, int r, int c, int cost){
        if(r<0 || r>=m || c<0 || c>=n || dp[r][c]!=-1) return;
        bfs.add(new int[]{r, c});
        dp[r][c] = cost;
        int next = grid[r][c]-1;
        dfs(grid, r+DIR[next][0], c+DIR[next][1], cost);
    }
}

 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
class Solution {
    public int minCost(int[][] grid) {
        int[][] dirs = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
        int m = grid.length;
        if (m == 0)
            return -1;
        int n = grid[0].length;
        if (n == 0)
            return -1;

        Queue<int[]> que = new LinkedList<>();
        que.add(new int[] { 0, 0 });
        int[][] cost = new int[m][n];// min cost to get here
        for (int i = 0; i < m; ++i)
            Arrays.fill(cost[i], Integer.MAX_VALUE);
        cost[0][0] = 0;

        while (!que.isEmpty()) {
            int[] cell = que.poll();
            int r = cell[0], c = cell[1], ct = cost[r][c];
            int dir = grid[r][c];
            for (int[] d : dirs) {
                int r1 = r + d[0], c1 = c + d[1];
                if (r1 < 0 || r1 >= m || c1 < 0 || c1 >= n)
                    continue;
                int ct1 = ct + (match(dir, r, c, r1, c1) ? 0 : 1);
                if (ct1 >= cost[r1][c1])
                    continue;
                cost[r1][c1] = ct1;
                que.add(new int[] { r1, c1 });
            }
        }

        return cost[m - 1][n - 1];
    }

    boolean match(int d, int r, int c, int r1, int c1) {
        if (d == 1 && r == r1 && c + 1 == c1)
            return true;
        if (d == 2 && r == r1 && c - 1 == c1)
            return true;
        if (d == 3 && r + 1 == r1 && c == c1)
            return true;
        if (d == 4 && r - 1 == r1 && c == c1)
            return true;
        return false;
    }
}

Wednesday, September 2, 2020

LeetCode [1376] Time Needed to Inform All Employees

 1376. Time Needed to Inform All Employees

Medium

A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company has is the one with headID.

Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also it's guaranteed that the subordination relationships have a tree structure.

The head of the company wants to inform all the employees of the company of an urgent piece of news. He will inform his direct subordinates and they will inform their subordinates and so on until all employees know about the urgent news.

The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e After informTime[i] minutes, all his direct subordinates can start spreading the news).

Return the number of minutes needed to inform all the employees about the urgent news.

 

Example 1:

Input: n = 1, headID = 0, manager = [-1], informTime = [0]
Output: 0
Explanation: The head of the company is the only employee in the company.

Example 2:

Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]
Output: 1
Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.
The tree structure of the employees in the company is shown.

Example 3:

Input: n = 7, headID = 6, manager = [1,2,3,4,5,6,-1], informTime = [0,6,5,4,3,2,1]
Output: 21
Explanation: The head has id = 6. He will inform employee with id = 5 in 1 minute.
The employee with id = 5 will inform the employee with id = 4 in 2 minutes.
The employee with id = 4 will inform the employee with id = 3 in 3 minutes.
The employee with id = 3 will inform the employee with id = 2 in 4 minutes.
The employee with id = 2 will inform the employee with id = 1 in 5 minutes.
The employee with id = 1 will inform the employee with id = 0 in 6 minutes.
Needed time = 1 + 2 + 3 + 4 + 5 + 6 = 21.

Example 4:

Input: n = 15, headID = 0, manager = [-1,0,0,1,1,2,2,3,3,4,4,5,5,6,6], informTime = [1,1,1,1,1,1,1,0,0,0,0,0,0,0,0]
Output: 3
Explanation: The first minute the head will inform employees 1 and 2.
The second minute they will inform employees 3, 4, 5 and 6.
The third minute they will inform the rest of employees.

Example 5:

Input: n = 4, headID = 2, manager = [3,3,-1,2], informTime = [0,0,162,914]
Output: 1076

 

Constraints:

  • 1 <= n <= 10^5
  • 0 <= headID < n
  • manager.length == n
  • 0 <= manager[i] < n
  • manager[headID] == -1
  • informTime.length == n
  • 0 <= informTime[i] <= 1000
  • informTime[i] == 0 if employee i has no subordinates.
  • It is guaranteed that all the employees can be informed.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    Map<Integer, Integer> timeToReachManager = new HashMap<>();
    int ret = 0;
    public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {
        timeToReachManager.put(n, 0);
        for(int i=0; i<n; ++i){
            helper(i, manager, informTime);
        }
        return ret;
    }

    int helper(int e, int[] manager, int[] informTime){
        if(timeToReachManager.containsKey(e)) return timeToReachManager.get(e);
        int m = manager[e];
        if(m==-1) return 0;
        int t = informTime[m] + helper(m, manager, informTime);
        timeToReachManager.put(e, t);
        ret = Math.max(ret, t);
        return t;
    }
}