Home >Backend Development >PHP Tutorial >Share an interesting PHP solution to an algorithm problem

Share an interesting PHP solution to an algorithm problem

藏色散人
藏色散人forward
2023-04-10 14:21:201462browse

This article brings you relevant knowledge about PHP. It mainly shares with you an interesting solution to an algorithm problem. There are code examples. Friends who are interested can take a look below. I hope it will be helpful to everyone.

Share an interesting PHP solution to an algorithm problem

#I recently saw it on Leetcode and it made my eyes light up.

Original link: https://leetcode.cn/problems/contains-duplicate/

Question

Give you an integer array nums. Returns true if any value appears at least twice in the array; returns false if each element in the array is distinct.

示例 1:

输入:nums = [1,2,3,1]
输出:true

示例 2:

输入:nums = [1,2,3,4]
输出:false

示例 3:

输入:nums = [1,1,1,3,3,4,3,2,4,2]
输出:true

Standard solution

    function containsDuplicate($nums) {

        foreach($nums as $val){
            if($repeat[$val] != ''){
                return true;
            }else{
                $repeat[$val] = $val;
            }
        }
        return false;

    }

Interesting solution

Principle: Roll two dice enough times, if they are the same , the description is repeated.

function containsDuplicate($nums) {
        $total = count($nums);

       for ($i=0; $i < 100000; $i++) {
           $a = mt_rand() % $total;
           $b = mt_rand() % $total;

            if($a != $b && ($nums[$a] == $nums[$b])){
                return true;
            }
       }

        return false;
    }

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Share an interesting PHP solution to an algorithm problem. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete