922. Sort Array By Parity II 976. Largest Perimeter Triangle

今天做了两道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);
	}
}

做第二题的时候想了一会,如果给一堆数字,三个三个判断太费时间了,不可能的。如果排序,从小到大,只看后三个,如果这三个数不能组成三角形,就摒弃最后一个,看倒数第四到倒数第二,以此列推。这样判断,就会好的多!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值