leetcode 976
给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、面积不为零的三角形的最大周长。
如果不能形成任何面积不为零的三角形,返回 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源码
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 }
来源:https://www.cnblogs.com/chenguifeng/p/12215189.html