Finding an element in an array where every element is repeated odd number of times (but more than single occurrence) and only one appears once

后端 未结 5 1436
闹比i
闹比i 2020-12-12 10:25

You have an array in which every number is repeated odd number of times (but more than single occurrence). Exactly one number appears once. How do you find the number that a

5条回答
  •  长情又很酷
    2020-12-12 11:04

    Test Score 100% with c#

    using System;
    using System.Collections.Generic;
    // you can also use other imports, for example:
    // using System.Collections.Generic;
    
    // you can write to stdout for debugging purposes, e.g.
    // Console.WriteLine("this is a debug message");
    
    class Solution {
        public int solution(int[] A) {
    
            Dictionary dic =new Dictionary();
    
            foreach(int i in A)
            {
                if (dic.ContainsKey(i))
                {
                    dic[i]=dic[i]+1;                
                }
                else
                {
                    dic.Add(i, 1);                
                }
            }
    
            foreach(var d in dic)
            {
                if (d.Value%2==1)
                {
                     return d.Key;
                }
            }
    
            return -1;
        }
    }
    

提交回复
热议问题