首页 > 试题广场 >

找不同

[编程题]找不同
  • 热度指数:1036 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
牛牛最近迷上了《找不同》这个小游戏,在这个游戏中,每一轮,会给你两张很相似的照片,需要你指出其中的所有不同之处。

这一天,牛牛玩着这个游戏,路过牛妹身旁,偶然间注意到牛妹正对着很多数字发呆。牛牛瞄了一眼数字,随手指了一个数字,说这个数字在这些数中只出现了一次。经过牛妹人工检验,发现牛牛说得对。

牛妹非常好奇牛牛的这个新能力,觉得是因为牛牛玩《找不同》玩多了,于是对于这类不同于其它的部分特别敏感。

为了进一步检测牛牛的能力,牛妹决定拟定一份问卷,让牛牛回答,每份问卷中有若干道题目,每道题目含有若干个数字,需要牛牛快速回答出,每道题所给的数字中,最小的一个只出现了一次的数字是什么?

由于题量很多,显然不能让牛妹人工核对答案,于是向你求助,希望你能给予牛妹帮助。

输入描述:
第一行输入一个正整数 ,代表这份问卷的题目总数。

对于每道题,第一行输入一个正整数 ,代表这道题中的数字个数。
第二行输入 个正整数 ,代表这道题中的每个数字。


输出描述:
对于问卷中的每道问题,一行输出一个整数代表答案;特殊的,如果不存在这样的数字,则输出  代表无解。
示例1

输入

2
3
6 6 6
3
6 9 6

输出

-1
9

说明

第一组测试数据,所有数字均为 \text 6,无解。
第二组测试数据,两个数字为 \text 6,一个数字为 \text 9,根据题意可以发现,答案为数字 \text 9.
对所有数字进行计数,然后对数字按升序排列,选择第一个计数为1的数输出就行
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));;
        int T = Integer.parseInt(br.readLine().trim());
        while(T -- > 0){
            int n = Integer.parseInt(br.readLine());
            String[] strNums = br.readLine().split(" ");
            int[] nums = new int[n];
            HashMap<Integer, Integer> counter = new HashMap<>();
            for(int i = 0; i < n; i++) {
                nums[i] = Integer.parseInt(strNums[i]);
                if(!counter.containsKey(nums[i]))
                    counter.put(nums[i], 1);
                else
                    counter.put(nums[i], counter.get(nums[i]) + 1);
            }
            Arrays.sort(nums);
            int res = -1;
            for(int num: nums){
                if(counter.get(num) == 1){
                    res = num;
                    break;
                }
            }
            System.out.println(res);
        }
    }
}

发表于 2021-07-23 11:54:41 回复(0)
用字典
num=input()
s=[input() for i in range(2*int(num))]
for i in range(len(s)):
    if i%2==1:
        a=s[i].strip().split(' ')
        n={}
        for key in a:
            n[key]=n.get(key,0)+1
        minvalue=[]
        if min(list(n.values()))==1:
            for key in n.keys():
                if n[key]==1:
                    minvalue.append(int(key))
            print(min(minvalue))
        else:
            print(-1)

发表于 2022-04-23 14:51:31 回复(0)
  • 用哈希表

    import java.util.*;
    import java.io.*;
    /**
    * @author Key
    * @date 2022/03/17/19:10
    **/
    public class Main {
      public static void main(String[] args) throws IOException {
          Scanner sc = new Scanner(System.in);
          BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    
          // 输入3.0:指定数据组数t,获取t组数据
          int t = sc.nextInt();
          while (t-- != 0) {
              int n = sc.nextInt();
    
              int[] nums = new int[n];
              for (int i = 0;i < n;i++) {
                  nums[i] = sc.nextInt();
              } 
              bw.write(getRes(n, nums) + "\n");
              bw.flush();
          }
      }
      // 核心代码
      private static int getRes(int n, int[] nums) {
    
          Map<Integer, Integer> map = new HashMap<>(n);
    
          for (int num : nums) {
              if (map.containsKey(num)) {
                  map.put(num, map.get(num) + 1);
              } else {
                  map.put(num, 1);
              }
          }
    
          int res = Integer.MAX_VALUE;
          for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
              int key = entry.getKey();
              int value = entry.getValue();
              if (value == 1) {
                  res = Math.min(res, key);
              }
          }
    
          return res == Integer.MAX_VALUE ? -1 : res;
      }
    }
发表于 2022-04-06 15:54:04 回复(0)
#include <iostream>
#include <map>

using namespace std;

int T, n;
map<int, int> h;

int main()
{
    cin >> T;
    while (T--) {
        h.clear();
        cin >> n;
        int x;
        for (int i = 0; i < n; ++i) {
            cin >> x;
            h[x]++;
        }
        int res = -1;
        for (auto it : h) {
            if (it.second == 1) {
                res = it.first;
                break;
            }
        }
        cout << res << endl;
    }
    return 0;
}

发表于 2022-02-08 22:20:58 回复(0)
#include <stdio.h>

int main() {
    int t; // 存储需要判断的组数
    scanf("%d", &t);

    while (t--) {
        int n; // 存储每组数据中的数字数量
        scanf("%d", &n);

        int freq[1001] = {0}; // 用于记录每个数字出现的频率,数字的范围为1到1000

        // 记录每个数字出现的频率
        for (int i = 0; i < n; ++i) {
            int num;
            scanf("%d", &num);
            freq[num]++;
        }

        // 找到只出现过一次的最小数字
        int minUnique = -1;
        for (int i = 1; i <= 1000; ++i) {
            if (freq[i] == 1) {
                minUnique = i;
                break;
            }
        }

        printf("%d\n", minUnique); // 输出结果
    }

    return 0;
}

发表于 2024-04-18 03:28:06 回复(0)
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        while (n-- > 0) {
            int m = sc.nextInt();
            int[] arr = new int[1005];
            for (int i = 0; i < m; i++) {
                arr[sc.nextInt()]++;
            }
            int i = 0;
            for (; i < arr.length; i++) {
                if (arr[i] == 1) {
                    break;
                }
            }
            if (i < arr.length) {
                System.out.println(i);
            } else {
                System.out.println(-1);
            }
        }
    }
}
发表于 2022-09-29 22:01:01 回复(0)
纯用列表(下标计数)
T = int(input())
for i in range(T):
    n = int(input())
    nums = list(map(int,input().split()))
    #找到个数为1的数,求最小
    count = [0]*1001
    res = []
    for j in nums:
        count[j] += 1 
    try:
        res.append(count.index(1))
    except:
        pass
    if res == []:
        print(-1)
    else:
        print(min(res))


发表于 2022-04-07 10:05:11 回复(0)
运行语言:Javascript_V8
跌跌撞撞地通过用例
var k = parseInt(readline());
var line1;
 
while(line1 = readline()){
    var nums = parseInt(line1.split(' ')[0])
    var a1 = readline().split(' ').map(Number)
    var flag =[]
    for(var i=0;i<nums;i++){
        if(flag[a1[i]]){
            flag[a1[i]]++
        }else{
            flag[a1[i]]=1
        }
    }
    for(var j in flag){
        if(flag[j] == 1){
            print(j)
            break
        }   
    }
    if( parseInt(j) == flag.length-1 && flag[flag.length-1] != 1){
        print(-1)
    }
                     
}


发表于 2022-04-07 00:00:42 回复(0)
while 1:
    try:
        n = int(input())
        for i in range(n):
            n1 = int(input())
            a = list(map(int,input().split()))
            dct = {}
            for i in a:
                if i not in dct:
                    dct[i] = 1
                else:
                    dct[i] += 1
            dct = list(dct.items())
            dct.sort(key = lambda x:(x[1],x[0]))
            if dct[0][1] == 1:
                print(dct[0][0])
            else:
                print(-1)
    except:
        break

发表于 2021-09-16 11:25:14 回复(0)
const { stdin, stdout } = require("process");
const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let inputs = [];
rl.on("line", function (data) {
  inputs.push(data);
  let num = inputs[0];
  let inputdata = inputs.slice(1);
  if (num * 2 == inputdata.length) {
    for (let i = 0; i < inputdata.length; i++) {
      if (i % 2 !== 0) {
        let inputToArr = inputdata[i].trim().split(" ");
        let isRightLength = parseInt(inputdata[i - 1]) === inputToArr.length;
        if (isRightLength) {
          let result = deal(inputToArr);
          console.log(result);
        }
      }
    }
  }
});

function deal(inputs) {
  inputs = inputs.map((item) => parseInt(item)).sort((a, b) => a - b);
  let length = inputs.length;
  let map = new Map();
  for (let i = 0; i < length; i++) {
    if (!map.has(inputs[i])) {
      map.set(inputs[i], 1);
    } else {
      map.set(inputs[i], map.get(inputs[i]) + 1);
    }
  }
  let res = [...map].filter((item) => item[1] === 1);
  if (!res.length) return -1;
  return res[0][0];
}

发表于 2021-08-27 12:24:17 回复(1)
import java.util.Scanner;

public class Main2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        int n = Integer.parseInt(s);
        int i = 0;
        while (i < n) {
            s = scanner.next();
            int x = Integer.parseInt(s);
            int j = 0;
            int[] num = new int[1001];
            while (j < x) {
                int a = scanner.nextInt();
                num[a]++;
                j++;
            }
            j = 0;
            int index = 1001;  //一次且最小的数字
            while (j < num.length) {
                if (1 == num[j]) {
                    if (index > j) {
                        index = j;
                    }
                }
                j++;
            }
            if (index == 1001) {
                index = -1;
                System.out.println(index);
            } else {
                System.out.println(index);
            }
            i++;
        }
    }
}

发表于 2021-07-02 22:45:34 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();

        int[] nums = new int[N];
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < N; i++) {
            nums[i] = scanner.nextInt();
            scanner.nextLine();
            list.add(scanner.nextLine());
        }

        for (int i = 0; i < N; i++) {
            String str = list.get(i);
            String[] split = str.split(" ");

            HashMap<Integer, Integer> map = new HashMap<>();
            for (String s : split) {
                int num = Integer.parseInt(s);
                map.put(num, map.getOrDefault(num, 0) + 1);
            }

            int min = Integer.MAX_VALUE;
            for (Integer integer : map.keySet()) {
                if (map.get(integer) == 1) {
                    if (integer < min) 
                        min = integer;
                }
            }
            
            if (min == Integer.MAX_VALUE) {
                System.out.println(-1);
            } else {
                System.out.println(min);
            }
        }
    }
}

发表于 2021-06-22 19:48:47 回复(0)
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int count = 0;
        int t = sc.nextInt();
        while(count<t){
            int n = sc.nextInt();
            Set<Integer> set = new HashSet();
            PriorityQueue p = new PriorityQueue();//优先队列会自动排序
            for(int i=0;i<n;i++){
                int temp = sc.nextInt();
                //要找到 唯一 且 最小 的数,把唯一的数通过set的判定,加进优先队列里
                if(set.add(temp)){
                    p.add(temp);
                }else{
                    p.remove(temp);
                }
            }
            if(p.size()==0){
                System.out.println("-1");
            }else{
                //优先队列里的第一个数(最小)
                System.out.println(p.poll());
            }
            count++;
        }        
    }
}

编辑于 2021-05-27 18:42:06 回复(0)

热门推荐

通过挑战的用户