笔试题:网易2016笔试题

===============================================================

1.Question

小明陪小红去看钻石,他们从一堆钻石中随机抽取两颗并比较她们的重量。这些钻石的重量各不相同。在他们们比较了一段时间后,它们看中了两颗钻石g1和g2。现在请你根据之前比较的信息判断这两颗钻石的哪颗更重。

给定两颗钻石的编号g1,g2,编号从1开始,同时给定关系数组vector,其中元素为一些二元组,第一个元素为一次比较中较重的钻石的编号,第二个元素为较轻的钻石的编号。最后给定之前的比较次数n。请返回这两颗钻石的关系,若g1更重返回1,g2更重返回-1,无法判断返回0。输入数据保证合法,不会有矛盾情况出现。

测试样例:
2,3,[[1,2],[2,4],[1,3],[4,3]],4

返回: 1

2.Algorithm

  扫描所有数组,如果有数组中第一个数为g1,第二个数为g2,直接判断

  扫描所有数组,如果有数组中第一个数为g2,第二个数为g1,直接判断

  扫描所有数组,如果有数组中第一个数为g1,记下第二个数num,看看其他数组中是否有这样的:第一个数为num,第二个数为g2,直接判断

  扫描所有数组,如果有数组中第一个数为g2,记下第二个数num,看看其他数组中是否有这样的:第一个数为num,第二个数为g1,直接判断

  除了以上情况,就不能进行判断。

3.Solution

import java.util.*;

public class Cmp {
    public int cmp(int g1, int g2, int[][] records, int n) {
        // write code here
        for(int i = 0; i < n; i++){
            if(records[i][0] == g1 && records[i][1] == g2){
                return 1;
            }
            if(records[i][0] == g2 && records[i][1] == g1){
                return -1;
            }
            
            if(records[i][0] == g1){
                int num = records[i][1];
                for(int j = 0; j < n; j++){
                    if(records[j][0] == num && records[j][1] == g2){
                        return 1;
                    }
                }
            }
            
            if(records[i][0] == g2){
                int num = records[i][1];
                for(int j = 0; j < n; j++){
                    if(records[j][0] == num && records[j][1] == g1){
                        return -1;
                    }
                }
            }
        }
        return 0;
    }
}

 

=============================================================== 

posted @ 2016-06-25 10:17  桃源仙居  阅读(411)  评论(0)    收藏  举报