zoukankan      html  css  js  c++  java
  • [topcoder]TheConsecutiveIntegersDivOne

    http://community.topcoder.com/stat?c=problem_statement&pm=13625&rd=16278

    首先,如果记得曼哈顿距离最小值那个问题,会想起一维的情况可证,点出现在中位数那里是最小的。这里也可证明,四个点,出现在中位数位置是最小的。

    题解里的做法是,试探所有让某个想减的绝对值最小的情况。

    我的代码有点丑,但过了:

    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    class TheConsecutiveIntegersDivOne {
    public:
    	int find(vector <int> numbers, int k) {
    		sort(numbers.begin(), numbers.end());
    		int d = k / 2;
    		int left = 0;
    		int sumL = 0;
    		for (int i = left; i < left + d; i++) {
    			sumL += numbers[i];
    		}
    		int sumR = 0;
    		int right = left + d;
    		if (k % 2 == 1) {
    			right++;
    		}
    		for (int i = right; i < right + d; i++) {
    			sumR += numbers[i];
    		}
    		int result = sumR - sumL - d * d;
    		while (right + d < numbers.size()) {
    			sumL += numbers[left + d];
    			sumL -= numbers[left];
    			sumR += numbers[right + d];
    			sumR -= numbers[right];
    			result = min(result, sumR - sumL - d * d);
    			left++;
    			right++;
    		}
    		return result;
    	}
    };
    

      

  • 相关阅读:
    在单机Hadoop上面增加Slave
    两台机器添加信任关系
    JS Scoping and Hoisting
    SCSS(SASS、CSS)学习
    程序的内存情况
    delete-node-in-a-bst
    serialize-and-deserialize-bst
    Linux Shell脚本编程--curl命令详解
    iOS文件保存策略
    浅谈spring——spring MVC(十一)
  • 原文地址:https://www.cnblogs.com/lautsie/p/4242975.html
Copyright © 2011-2022 走看看