码迷,mamicode.com
首页 > 其他好文 > 详细

217_Contains Duplicate

时间:2015-12-25 19:09:38      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

217_Contains Duplicate

标签:

原文地址:http://www.cnblogs.com/Anthony-Wang/p/5076485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!