rust sort

lihn 2020-01-19

leetcode 976

给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、面积不为零的三角形的最大周长。

如果不能形成任何面积不为零的三角形,返回 0

impl Solution {
    pub fn largest_perimeter(a: Vec<i32>) -> i32 {
        let mut a = a;
        a.sort_by(|a, b| b.cmp(&a));
        for i in 0..a.len()-2 {
            if a[i] < a[i+1] + a [i+2] {
                return a[i] + a[i+1] + a[i+2];
            }
        }
        0
    }
}

sort_by源码

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

相关推荐

whats / 0评论 2011-04-10