lintcode(399)Nuts 和 Bolts 的问题

Description:

给定一组 n 个不同大小的 nuts 和 n 个不同大小的 bolts。nuts 和 bolts 一一匹配。 不允许将 nut 之间互相比较,也不允许将 bolt 之间互相比较。也就是说,只许将 nut 与 bolt 进行比较, 或将 bolt 与 nut 进行比较。请比较 nut 与 bolt 的大小。

Explanation:

给出 nuts = ['ab','bc','dd','gg'], bolts = ['AB','GG', 'DD', 'BC']
你的程序应该找出bolts和nuts的匹配。
一组可能的返回结果是:
nuts = ['ab','bc','dd','gg'], bolts = ['AB','BC','DD','GG']
我们将给你一个匹配的比较函数,如果我们给你另外的比较函数,可能返回的结果是:
nuts = ['ab','bc','dd','gg'], bolts = ['BC','AB','DD','GG']

因此的结果完全取决于比较函数,而不是字符串本身。
因为你必须使用比较函数来进行排序。
各自的排序当中nuts和bolts的顺序是无关紧要的,只要他们一一匹配就可以。

Solution:

Search the element in bolts that equals the nuts[i], and then swap the bolts[i] with bolts[current],one pass in nuts.

We use compare.cmp() to judge whether equals or not.

/**
 * public class NBCompare {
 *     public int cmp(String a, String b);
 * }
 * You can use compare.cmp(a, b) to compare nuts "a" and bolts "b",
 * if "a" is bigger than "b", it will return 1, else if they are equal,
 * it will return 0, else if "a" is smaller than "b", it will return -1.
 * When "a" is not a nut or "b" is not a bolt, it will return 2, which is not valid.
*/
public class Solution {
    /**
     * @param nuts: an array of integers
     * @param bolts: an array of integers
     * @param compare: a instance of Comparator
     * @return: nothing
     */
    public void sortNutsAndBolts(String[] nuts, String[] bolts, NBComparator compare) {
        // write your code here
        for(int i = 0;i<nuts.length;i++){
            for(int j = i;j<bolts.length;j++){
                int record = compare.cmp(nuts[i] , bolts[j]);
                if(record == 0){
                    swap(bolts , j , i);
                    break;
                }
            }
        }
    }
    
    public void swap(String[] bolts , int start , int end){
        String temp = bolts[start];
        bolts[start] = bolts[end];
        bolts[end] = temp;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值