码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] String Reorder Distance Apart

时间:2015-01-18 15:51:15      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:leetcode

Question:

Given a string of lowercase characters, reorder them such that the same characters are at least distance d from each other.


Input: { a, b, b }, distance = 2

Output: { b, a, b }


http://leetcode.com/2010/05/here-is-another-google-phone-interview.html

public void reorder(int[] A, int d)
{
    // Stats
    Map<Integer, Integer> map = new HashMap<>();
    for (int i : A) 
    {
        Integer occurance = map.get(i);
        if (occurance == null)
            occurance = 0;
        occurance++;
        map.put(i, occurance);
    }
    
    // Sort
    List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>()
    {
        public int compare(Entry<Integer, Integer> a, Entry<Integer, Integer> b) 
        {
            return -1 * Integer.compare(a.getValue(), b.getValue());
        }
    });
    
    // Re-assign
    int curIndex = 0;
    Map.Entry<Integer, Integer> cur = list.get(curIndex);
    int curOccurance = 0;
    for (int offset = 0; offset < d; offset++)
    {
        for (int i = offset; i < A.length; i += d)
        {
            A[i] = cur.getKey();
            curOccurance++;
            
            if (curOccurance == cur.getValue())
            {
                curIndex++;
                if (curIndex == list.size())
                    return;
                cur = list.get(curIndex);
                curOccurance = 0;
            }
        }
    }
}


[LeetCode] String Reorder Distance Apart

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1605271

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!