zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    链接唤醒IOSApp
    C#抽象属性
    c#结构体与类的区别
    广告学入门
    个性化推荐十大挑战[
    MapReduce 读取和操作HBase中的数据
    mysql sql命令大全
    从B 树、B+ 树、B* 树谈到R 树
    MapReduce操作HBase
    Meanshift,聚类算法
  • 原文地址:https://www.cnblogs.com/Anthony-Wang/p/5076485.html
Copyright © 2011-2022 走看看