1. Contains Duplicate--217
用hashset来判断,所以感觉遇到这种寻找重复类的问题,就用hashset
class Solution {
public boolean containsDuplicate(int[] nums) {
boolean result = false;
HashSet<Integer> set = new HashSet<>();
for(int i: nums){
set.add(i);
}
if(set.size() != nums.length){
result = true;
}
return result;
}
}
如何更好一点呢?在这里不用add所有i,一旦发现hashset里面有i,就可以return true了,最后如果都没有就return false
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> hset = new HashSet<>();
for(int i: nums){
if(hset.contains(i)){
return true;
}
hset.add(i);
}
return false;
}
}
2. Meeting Rooms--252
一开始想的很简单,只要去比较current_start和previous_end就可以了。但是没有这么简单,比如
[[7,10],[2,4]]这个例子是可以的,如果按照current_start和previous_end比较的话,结果会是错的。
可以先sort by start time,然后再用这个方法。那如何在Java里面实行这个sort呢?
Arrays.sort(intervals, (a,b) -> Integer.compare(a[0], b[0]));
整体代码
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
Arrays.sort(intervals, (a,b) -> Integer.compare(a[0], b[0]));
for(int i=1; i<intervals.length; i++){
int current_start = intervals[i][0];
int previous_end = intervals[i-1][1];
if(previous_end > current_start){
return false;
}
}
return true;
}
}
Time Complexity: O(n logn) ->The time complexity is dominated by sorting. Once the array has been sorted, only O(n) time is taken to go through the array and determine if there is any overlap.
3. Move Zeroes --283
看到以后没什么思路,先谢谢brute force的解法
class Solution {
public void moveZeroes(int[] nums) {
for(int i=0; i<nums.length; i++){
for(int j=i; j<nums.length; j++){
if(nums[i] == 0 && nums[j] != 0){
nums[i] = nums[j];
nums[j] = 0;
}
}
}
}
}
Time Complexity = O(n^2)
后面看别人的solution,这个更容易理解。如果没有0,那整个array就没有变,有0就replace到0的位置,后面再加上就好了
class Solution {
public void moveZeroes(int[] nums) {
int n=0;
for(int i: nums){
if(i != 0){
nums[n]=i;
n++;
}
}
while(n < nums.length){
nums[n++] = 0;
}
}
}
Time Complexity = O(n + #num of zero)
4. Squares of a Sorted Array--977
最暴力的方式--都square了以后在sort,Time Complexity O(n logn) -> sorts takes O(n logn) and square takes O(n)
想想怎么找到O(n) solution, 可以利用two pointers
class Solution {
public int[] sortedSquares(int[] nums) {
int[] ans = new int[nums.length];
int count = nums.length-1;
int left=0;
int right = nums.length-1;
while(left <= right){
int a = Math.abs(nums[left]);
int b = Math.abs(nums[right]);
if(a >= b){
ans[count--] = a*a;
left++;
}else{
ans[count--] = b*b;
right--;
}
}
return ans;
}
}
Time Complexity = O(n)