Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Idea is, among all factors of the int, we pick the two that is the closest pair. And searching from sqrt(area) is a better idea: 

https://discuss.leetcode.com/topic/76314/3-line-clean-and-easy-understand-solution

class Solution {
public:
    vector<int> constructRectangle(int area) {
        //defactor
        vector<int> ret;
        if(area<1) return ret;
        
        int i = 1;
        while(i <= area)
        {
            if(area % i == 0)
            {
                int a = i;
                int b = area /i;
                if(a>b) break;
                if(a==b) return {a,b};
                ret = {b, a};
            }
            i++;
        }
        
        return ret;
    }
};
posted on 2017-01-24 11:05  Tonix  阅读(199)  评论(0编辑  收藏  举报