leetcode-转变数组后最接近目标值的数组和

class Solution {
    public int findBestValue(int[] arr, int target) {
        int length = arr.length;
        Arrays.sort(arr);
        int minindex = -1;
        int mincount = -1;
        for(int i=0;i<=target;i+=1){
            int count = 0;
            for(int k=0;k<length;k+=1){
                int num = arr[k];
                if(num>i){
                    count += (length-k)*i;
                    break;
                }
                else{
                    count +=arr[k];
                }
            }
            if(count == target){
                return i;
            }
            if(minindex == -1){
                minindex = i;
                mincount = count;
            }
            else{
                if(Math.abs(mincount-target)>Math.abs(count-target)){
                    minindex = i;
                    mincount = count;
                }
            }
        }
        return minindex;
    }
}

leetcode-双周赛的题目

其实看到数组的题,特别是这种元素总和之类,如果对数组进行排序后不会影响题意,那么排序肯定是能对求解有帮助的。

当然,我的算法虽然能ac,但时间复杂度较高,其他选手有用二分查找的。

发布了48 篇原创文章 · 获赞 0 · 访问量 4339

猜你喜欢

转载自blog.csdn.net/weixin_41327340/article/details/103753461