976. triangular maximum perimeter (utilization of bubble sort)

This question is in the brush, inspired others, and to improve a bit on its basis.

1. The necessary and sufficient conditions are trilateral form a triangle: two sides of a smaller side than the third

2. Arrays.sort (), time complexity is O ( n- 2 )

3. Here a bubble sort, the best result is sorted 3 times, time with 3N , worst n- 2

4. The bubble sort method, when a trip is not exchanged, the sort is complete. Here copied from, but not directly out of the loop or to continue to compare whether the triangle.

 

 1 class Solution {
 2     public int largestPerimeter(int[] A) {
 3         Arrays.sort(A);
 4         for(int i = A.length-1; i >= 2; i--){
 5             if( (A[i-1] + A[i -2] > A[i])  )
 6                return A[i] + A[i-1] + A[i-2];
 7         }
 8          return 0;
 9     }
10 }

After improved bubble sort:

 1 class Solution {
 2     public int largestPerimeter(int[] A) {
 3         boolean mark = true;
 4         for(int i = 1; i < A.length; i++){
 5             if(mark){
 6                 mark = false;
 7                 for(int j = 0; j < A.length - i; j++){
 8                     if(A[j+1] < A[j]){
 9                         int tmp = A[j];
10                         A[j] = A[j+1];
11                         A[j+1] = tmp;
12                         mark = true;
13                     }
14                 }
15             }
16             
17             if(i>=3){
18                 if(A[A.length-i] + A[A.length-i+1] > A[A.length-i+2] )
19                     return A[A.length-i] + A[A.length-i+1] + A[A.length-i+2];
20             }
21         }
22         
23         if(A[0] + A[1] >A[2]) return A[0] + A[1] + A[2];
24         else  return 0 ;
25      }
 26 }

 

Guess you like

Origin www.cnblogs.com/leechee9/p/11790853.html