今天做了两道easy题,我专门挑的sort种类的题,都做出来了,比较高兴了!
做第二道题的时候,我用了快速排序的方法,快速排序怎么写了已经忘了,专门上网看了看,学习了学习,明天需要巩固!
922. Sort Array By Parity
Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.
Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
You may return any answer array that satisfies this condition.
class Solution {
public int[] sortArrayByParityII(int[] A) {
int num = A.length;
int[] copyA = new int[num];
int m = 0, n = 1;
for(int val : A) {
if(val % 2 == 0) {
copyA[m] = val;
m += 2;
}else {
copyA[n] = val;
n += 2;
}
}
return copyA;
}
}
976. Largest Perimeter Triangle
Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.
If it is impossible to form any triangle of non-zero area, return 0.
class Solution {
public int largestPerimeter(int[] A) {
int n = A.length;
QuickSort(A,0,n-1);
for(int i = n-1 ; i-2 >= 0 ; i--) {
if ((A[i] + A[i-1] > A[i-2]) && (A[i-2] + A[i-1] > A[i]) && (A[i] + A[i-2] > A[i-1])) {
return A[i] + A[i-1] + A[i-2];
}
}
return 0;
}
public void QuickSort(int[] A, int start, int end) {
if(start >= end) return;
int i = start;
int j = end;
int baseval = A[start];
while(i < j) {
while(i < j && A[j] >= baseval ) j--;
if(i < j) {
A[i] = A[j];
i++;
}
while(i < j && A[i] < baseval ) i++;
if(i < j) {
A[j] = A[i];
j--;
}
}
A[i] = baseval;
QuickSort(A,start,i-1);
QuickSort(A,i+1,end);
}
}
做第二题的时候想了一会,如果给一堆数字,三个三个判断太费时间了,不可能的。如果排序,从小到大,只看后三个,如果这三个数不能组成三角形,就摒弃最后一个,看倒数第四到倒数第二,以此列推。这样判断,就会好的多!