1396. Design Underground System

An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.

Implement the UndergroundSystem class:

  • void checkIn(int id, string stationName, int t)
    • A customer with a card ID equal to id, checks in at the station stationName at time t.
    • A customer can only be checked into one place at a time.
  • void checkOut(int id, string stationName, int t)
    • A customer with a card ID equal to id, checks out from the station stationName at time t.
  • double getAverageTime(string startStation, string endStation)
    • Returns the average time it takes to travel from startStation to endStation.
    • The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.
    • The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.
    • There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.
      You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.

两个哈希表,第一个暂存id。第二个用来储存“站点——站点”和路线中的总用时,路线中的总人数。
最后返回总用时除以总人数。
(一开始采用的算法没有考虑id重复进站,和id出站进站不同的情况。)

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
class UndergroundSystem {
HashMap<Integer, Pair<String, Integer>> inMap;
HashMap<String, int[]> outMap;
public UndergroundSystem() {
inMap = new HashMap<Integer, Pair<String, Integer>>();
outMap = new HashMap<String, int[]>();
}

public void checkIn(int id, String stationName, int t) {
Pair<String, Integer> data = new Pair(stationName, t);
inMap.put(id, data);
}

public void checkOut(int id, String stationName, int t) {
Pair<String, Integer> data = inMap.get(id);
String route = data.getKey() + "-" + stationName;

int[] routeData = outMap.getOrDefault(route, new int[2]);
routeData[0] += t - data.getValue();
routeData[1]++;

outMap.put(route, routeData);
}

public double getAverageTime(String startStation, String endStation) {
String route = startStation + "-" + endStation;
return outMap.get(route)[0] / (double) outMap.get(route)[1];
}
}

/**
* Your UndergroundSystem object will be instantiated and called as such:
* UndergroundSystem obj = new UndergroundSystem();
* obj.checkIn(id,stationName,t);
* obj.checkOut(id,stationName,t);
* double param_3 = obj.getAverageTime(startStation,endStation);
*/

78. Subsets

Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

回溯,先添加一个空集,然后回溯各个单独节点。
递归时传入数组内当前数字之后的节点。

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
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
ret.add(new ArrayList<>());

for(int i = 0; i < nums.length ; i++){
backtrack(ret, new ArrayList<>(), nums, i);
}
return ret;
}

private void backtrack(List<List<Integer>> ret, List<Integer> arr, int[] nums, int i){
if(i == nums.length-1){
arr.add(nums[i]);
ret.add(new ArrayList<>(arr));
return;
}

arr.add(nums[i]);
ret.add(new ArrayList<>(arr));
for(int j = i+1; j < nums.length; j++){
backtrack(ret, arr, nums, j);
arr.remove(arr.size()-1);
}
}
}

43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

两个字符串的位数做乘法,每次计算进位。
当前位等于自身加上计算结果的个位(由于有之前的进位存在。),下一位等于计算结果的十位。

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
class Solution {
public String multiply(String num1, String num2) {
int m = num1.length();
int n = num2.length();
if( num1.equals("0") || num2.equals("0")){
return "0";
}
int[] product = new int[m+n];

char[] arr1 = num1.toCharArray();
char[] arr2 = num2.toCharArray();

for(int i = m-1; i >= 0; i--){
for(int j = n-1; j >=0; j--){
int sum = product[i+j+1] + (arr1[i] - '0') * (arr2[j] - '0');
int curr = sum % 10;
int carry = sum / 10;

product[i+j] += carry;
product[i+j+1] = curr;
}
}
StringBuffer sb = new StringBuffer();
for(int k = 0; k < m+n; k++ ){
if(k == 0 && product[k] == 0 ) continue;
sb.append(product[k]);
}
return sb.toString();
}
}

49. Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

利用JAVA中字符串会固定内存地址。(因此在进行字符串操作时是生成了新的对象。)
遍历每个单词,记录26个字母出现的次数,并映射到字符数组上。
将字符数组转换成字符串,生成一个新的字符串。

将字符串作为key放入map中,value储存原有单词。(字符串的内存地址固定,因此同样的字符串可以被搜索到。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ret = new ArrayList<>();
HashMap<String, List<String>> map = new HashMap<>();

for(String word : strs){
char[] alphabet = new char[26];
for(int j = 0; j < word.length(); j++){
alphabet[word.charAt(j)-'a']++;
}
String s = new String(alphabet);
List<String> str = map.getOrDefault(s, new ArrayList<String>());
str.add(word);
map.put(s, str);
}
for(String key : map.keySet()){
ret.add(map.get(key));
}
return ret;
}
}

797. All Paths From Source to Target

Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.

The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).

回溯。DFS搜索所有的路径。
当搜索到最后一个位置时,保存动态数组并返回。(此处需要深拷贝数组。)
回到上一层,取走动态数组的最后一个节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> ret = new LinkedList<>();
dfs(ret, new ArrayList<>(), graph, 0);
return ret;
}

private void dfs(List<List<Integer>> ret, List<Integer> arr, int[][] graph, int i){
if( i == graph.length - 1){
arr.add(i);
ret.add(new ArrayList(arr));
return;
}
arr.add(i);
for( int j : graph[i] ){
dfs(ret, arr, graph, j);
arr.remove(arr.size()-1);
}
}
}