LeetCode 找到 K 个最接近的元素—个人方法分享

112 阅读1分钟

石之海3.jpg

个人觉得这是隐藏在中等题中的简单题。写出了三种解答思路,供大家参考。


第一种解题思路

双指针,排除法,因为已经是有序的数组。 只要用两个指针分别在头和尾进行比对,哪头绝对值大就移除哪个。 最后可以直接返回。

代码

public class Solution {
    public IList<int> FindClosestElements(int[] arr, int k, int x) 
    {
        List<int> list = arr.ToList();
        int left = 0;
        int right = list.Count - 1;
        while (list.Count > k)
        {
            right = list.Count - 1;
            if (Math.Abs(list[left] - x) > Math.Abs(list[right] - x))
                list.RemoveAt(left);
            else if (Math.Abs(list[left] - x) < Math.Abs(list[right] - x)||
                Math.Abs(list[left] - x)== Math.Abs(list[right] - x)&&
                list[left]< list[right])
            {
                list.RemoveAt(right);
            }
            else if(Math.Abs(list[left] - x) == Math.Abs(list[right] - x))//以防止有相同元素的用例
            {
                list.RemoveAt(right);
            }
        }
        return list;

    }

第二种解题思路

调用API+Linq。 复写Array.Sort方法,根据题意自定义规则。 最后用Linq获取指定长度再进行排序,返回。

代码

public class Solution {
    public IList<int> FindClosestElements(int[] arr, int k, int x) 
    {
        //如果返回值>0为大于,如果小于0为小于,=0为相等。
        Array.Sort(arr,(a,b)=>{
            if(Math.Abs(a-x)!=Math.Abs(b-x))
                return Math.Abs(a-x)-Math.Abs(b-x);
            else
                return a-b;

        });
        arr=arr.Take(k).OrderBy(a=>a).ToArray();
        return arr;
    }
}

第三种解题思路

Linq一句解决。 以绝对值大小排序,越小越接近x,越靠前,最后截取k个长度,再排序一下,转成List返回。

代码

public class Solution {
    public IList<int> FindClosestElements(int[] arr, int k, int x) 
    {
        return arr.OrderBy(num=>Math.Abs(x-num)).Take(k).OrderBy(n=>n).ToList();
    }
}