A Straightforward C# solution & an error on OJ


  • 0

    Straightforward AC solution.

    Use a hash table to store the input.
    Key: actual value; Value: the number of appearances.

    (To minimize the space used for this particular problem, could use a bool value to mark whether the number appear more than twice.)

    public class TwoSum {
         
        private Dictionary<int, int> dict;
        /** Initialize your data structure here. */
        public TwoSum() {
            dict = new Dictionary<int,int>();
        }
        
        /** Add the number to an internal data structure.. */
        public void Add(int number) {
    
            if(!dict.ContainsKey(number))
               dict.Add(number, 1);
            else
               dict[number]++;
        }
        
        /** Find if there exists any pair of numbers which sum is equal to the value. */
        public bool Find(int value) {
            
            bool found = false;
            
            foreach (var entry in dict)
            {
                int aim = value - entry.Key;
                if (dict.ContainsKey(aim))
                {
                    if (aim != entry.Key || entry.Value >= 2) return true;
                }
            }
            return found;
        }
    }
    

    A OJ error occurs when I run/submit the code. (Same input, different expected answers from Run and Submit)

    0_1495077721054_捕获.JPG


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.