Shortest Word Distance
☆☆☆☆☆
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “coding”, word2 = “practice”, return 3. Given word1 = "makes", word2 = "coding", return 1.
Note: You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
public int shortestDistance(String[] words, String word1, String word2) {
int idx1 = -1;
int idx2 = -1;
int distance = words.length;
for (int i = 0; i < words.length; ++i) {
if (words[i].equals(word1)) idx1 = i;
if (words[i].equals(word2)) idx2 = i;
if (idx1 != -1 && idx2 != -1) distance = Math.min(Math.abs(idx1 - idx2), distance);
}
return distance;
}
Move Zeroes
★★☆☆☆
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.
Note: zero's order is not important at allllll!
public void moveZeroes(int[] nums) {
int insertPt = 0;
for (int num: nums) {
if (num != 0) {
nums[insertPt++] = num;
}
}
for (int i = insertPt; i < nums.length; ++i) {
nums[i] = 0;
}
}
Meeting Rooms
★☆☆☆☆
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.
For example, Given [[0, 30],[5, 10],[15, 20]], return false.
public boolean canAttendMeetings(Interval[] intervals) {
Arrays.sort(intervals, (Interval i1, Interval i2) -> i1.end - i2.end);
for (int i = 1; i < intervals.length; ++i) {
if (intervals[i].start < intervals[i-1].end) return false;
}
return true;
}
Summary Ranges
★★☆☆☆
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
Harder when you loop, easily make it too complicated...
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
for(int i = 0; i < nums.length; ++i) {
int begin = i;
while (i + 1 < nums.length && nums[i+1] == nums[i] + 1) ++i;
if (i == begin) res.add(String.valueOf(nums[begin]));
else res.add(nums[begin] + "->" + nums[i]);
}
return res;
}