26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array

Question

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k* after placing the final result in the first k slots of *nums.

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

Solution

由于数组本身已经排序,只要比较当前nums中的元素是否大于上一个保存的数值就可以决定是否保留。
创建一个k记录遍历的位置,每次比较nums[k]与nums[i]的位置元素的大小,如果当前的nums[i]大于nums[k],则将k位置向后移动1,并将下一个位置记录为nums[i]。

最后返回k+1。

Code

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int removeDuplicates(int[] nums) {
int k = 0;
for(int i = 0; i < nums.length; i++){
if(nums[k] < nums[i]){
k++;
nums[k] = nums[i];
}
}
return k + 1;
}
}

Recursive Relation, LHRC, Honoi Tower

Find closed formula for an.

  1. Iteration (Proof by Induction)
  2. Linear homogeneous recursive relation with constant coefficiens (LHRC)
    find the roots of equation t2+c1t+C2
    then where exist constants b, d such that an = br1n+dr2n, for n >= 0

Recursive Relation, Honoi Tower, LHRC

1578. Minimum Time to Make Rope Colorful

1578. Minimum Time to Make Rope Colorful

Problem

Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the i<sup>th</sup> balloon.

Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the i<sup>th</sup> balloon from the rope.

Return the minimum time Bob needs to make the rope colorful.

Solution

滑动窗口,遍历字符串。
common用来记录连续颜色相同的个数,初始化为1。
如果当前字符与下一个字符相同,则窗口向右侧扩展,common++。
遍历时记录替换气球需要的最大时间maxTime和替换掉所有同色气球的总时间deleteTime。

如果common大于1,则总时间加上需要删除的时间(刨除最大时间maxTime)。
更新i为i + common。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int minCost(String colors, int[] neededTime) {
int i = 0, totalTime = 0;
char[] c = colors.toCharArray();
while(i < neededTime.length){
int common = 1, maxTime = neededTime[i], deleteTime = neededTime[i];
while(i + common < neededTime.length && c[i] == c[i + common]){
maxTime = Math.max(maxTime, neededTime[i + common]);
deleteTime += neededTime[i + common];
common++;
}
if(common > 1){
deleteTime -= maxTime;
totalTime += deleteTime;
}
i += common;
}
return totalTime;
}
}

609. Find Duplicate File in System

Question

Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.

A group of duplicate files consists of at least two files that have the same content.

A single directory info string in the input list has the following format:

  • "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"

It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory “root/d1/d2/.../dm". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.

The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:

  • "directory_path/file_name.txt"

Solution

使用StringBuffer对字符串进行处理。
采用HashMap建立内容和对应列表的映射。

遍历处理字符串,并添加到map中。
最后遍历map,如果对应的列表size大于1,则加入结果。

Code

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
class Solution {
public List<List<String>> findDuplicate(String[] paths) {
List<List<String>> res = new ArrayList<>();
HashMap<String, List<String>> map = new HashMap<>();

for(String path : paths){
StringBuffer folder = new StringBuffer();

int i = 0;
while(path.charAt(i) != ' '){
folder.append(path.charAt(i));
i++;
}
while(i < path.length()){
while(path.charAt(i) == ' ') i++;
StringBuffer filename = new StringBuffer();
while(i < path.length() && path.charAt(i) != '('){
filename.append(path.charAt(i));
i++;
}

StringBuffer content = new StringBuffer();
while(i < path.length() && path.charAt(i) != ')'){
content.append(path.charAt(i));
i++;
}
i++;
List<String> arr = map.getOrDefault(content.toString(), new ArrayList<String>());
arr.add(folder.toString() + '/' + filename);
map.put(content.toString(), arr);
}
}

for(String content : map.keySet()){
if(map.get(content).size() > 1) res.add(map.get(content));
}

return res;
}
}
42. Trapping Rain Water

42. Trapping Rain Water

Question

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Solution

双指针,设置当前左侧的最大高度left和右侧的最大高度right。

分别从两侧遍历height[]数组,当出现更高的height时更新left和right。
否则记录left和right与height[i]的差值,并记录在数组waterLeft[]和waterRight[]中。

遍历两个数组,添加两者中的最小值到volume。

*由于单个参数只记录了一侧的最大值,因此最大值另一侧的水的体积会被多计算,因此分别从两侧遍历来获得最小值。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int trap(int[] height) {
int n = height.length, left = 0, right = 0, volume = 0;
int[] waterLeft = new int[n], waterRight = new int[n];

for(int i = 0; i < n; i++){
if(left <= height[i]) left = height[i];
else waterLeft[i] = left - height[i];
}

for(int i = n - 1; i >= 0; i--){
if(right <= height[i]) right = height[i];
else waterRight[i] = right - height[i];
}

for(int i = 0; i < n; i++){
volume += Math.min(waterLeft[i], waterRight[i]);
}

return volume;
}
}