思路:
class Solution {
public int[][] merge(int[][] intervals) {
// 先按照数组中第一个元素进行升序排序
Arrays.sort(intervals,new Comparator<int[]>(){
@Override
public int compare(int[] o1,int[] o2){
return o1[0] - o2[0];
}
});
//初始化outputs数组,用于存储合并之后区间结果的动态数组
ArrayList<int[]> output = new ArrayList<>();
//循环遍历数组
for(int i =0;i < intervals.length;i++){
int[] currArry = intervals[i];
if(output.size() == 0){
//第一次进来没有数据的时候,直接添加
output.add(currArry);
}else{
//get last eum
int[] lastArry = output.get(output.size() -1);
int lastArryRight = lastArry[1];
int currArryLeft = currArry[0];
if(lastArryRight < currArryLeft){
// 么有交集
output.add(currArry);
}else{
int currArryRight = currArry[1];
int maxRight = Math.max(lastArryRight,currArryRight);
lastArry[1] = maxRight;
}
}
}
return output.toArray(new int[output.size()][]);
}
}
思路
class Solution {
public void sortColors(int[] nums) {
//使用计数排序算法
int[] count = new int[3];
for(int i = 0 ; i < nums.length;i++){
count[nums[i]]++;
}
//2.排序
int k = 0 ;
// 题目写死了就三个数
for(int i = 0 ; i <=2 ;i++){
// 每个元素的个数
int num = count[i];
// 将元素复制到原数组中
for(int j = 1; j <= num; j++){
nums[k++] = i;
}
}
}
}
方法二:
使用三路快排方法
class Solution {
public void sortColors(int[] nums) {
// 三路快排方法
int zero = 0 ;
int two = nums.length -1;
int i = 0 ;
while (i <= two){
if(nums[i] == 0){
int temp = nums[zero];
nums[zero] = nums[i];
nums[i] = temp;
zero++;
i++;
}else if(nums[i] == 2){
int temp = nums[two];
nums[two] = nums[i];
nums[i] = temp;
two--;
}else{
i++;
}
}
}
}