217_Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

给定一个数组,判断这个数组是否有重复的元素,有则返回真,无则返回假

用哈希表,只要在相同的位置向后 .next 计算是否有重复即可。注意:取模操作可能会得到一个负数,所以需要绝对值来计算位置(因为数组没有实际意义,是给定的数字,可能会有负数)

public class Solution {
    public class Node
    {
        public Node(int i)
        {
            this.number = i;
        }
        public int number;
        public Node next;
    }
    
    public bool ContainsDuplicate(int[] nums) {
        int key = nums.Count();
        Node[] hashTable = new Node[nums.Count()];
        
        for(int i = 0; i < nums.Count(); i++)
        {
            int location = System.Math.Abs(nums[i] % key);
            Node newNode = new Node(nums[i]);
            
            if(hashTable[location] == null)
            {
                hashTable[location] = newNode;
            }
            else
            {
                Node cursorNode = hashTable[location];
                while(cursorNode != null)
                {
                    if(cursorNode.number == nums[i])
                    {
                        return true;
                    }
                    if(cursorNode.next != null)
                    {
                        cursorNode = cursorNode.next;
                    }
                    else
                    {
                        cursorNode.next = newNode;
                        break;
                    }
                }
            }
        }
        return false;
    }
}
原文地址:https://www.cnblogs.com/Anthony-Wang/p/5076485.html