rust sort

leetcode 976

To the array by a number of positive (representative length) of a given composition  A, wherein the three returned by the maximum perimeter length of the composition, the area of the triangle is not zero.

If not form any non-zero area triangles return  0.

 1 impl Solution {
 2     pub fn largest_perimeter(a: Vec<i32>) -> i32 {
 3         let mut a = a;
 4         a.sort_by(|a, b| b.cmp(&a));
 5         for i in 0..a.len()-2 {
 6             if a[i] < a[i+1] + a [i+2] {
 7                 return a[i] + a[i+1] + a[i+2];
 8             }
 9         }
10         0
11     }
12 }

sort_by source

 1 /// # Examples
 2     ///
 3     /// ```
 4     /// let mut v = [5, 4, 1, 3, 2];
 5     /// v.sort_by(|a, b| a.cmp(b));
 6     /// assert!(v == [1, 2, 3, 4, 5]);
 7     ///
 8     /// // reverse sorting
 9     /// v.sort_by(|a, b| b.cmp(a));
10     /// assert!(v == [5, 4, 3, 2, 1]);
11     /// ```
12     #[stable(feature = "rust1", since = "1.0.0")]
13     #[inline]
14     pub fn sort_by<F>(&mut self, mut compare: F)
15         where F: FnMut(&T, &T) -> Ordering
16     {
17         merge_sort(self, |a, b| compare(a, b) == Less);
18     }

Guess you like

Origin www.cnblogs.com/chenguifeng/p/12215189.html