php: check if an array has duplicates

前端 未结 15 2421
情深已故
情深已故 2020-11-27 04:07

I\'m sure this is an extremely obvious question, and that there\'s a function that does exactly this, but I can\'t seem to find it. In PHP, I\'d like to know if my array has

15条回答
  •  没有蜡笔的小新
    2020-11-27 04:41

    Two ways to do it efficiently that I can think of:

    1. inserting all the values into some sort of hashtable and checking whether the value you're inserting is already in it(expected O(n) time and O(n) space)

    2. sorting the array and then checking whether adjacent cells are equal( O(nlogn) time and O(1) or O(n) space depending on the sorting algorithm)

    stormdrain's solution would probably be O(n^2), as would any solution which involves scanning the array for each element searching for a duplicate

提交回复
热议问题