Share an interesting PHP solution to an algorithm problem

藏色散人
Release: 2023-04-11 16:36:01
forward
1430 people have browsed it

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
Copy after login

Standard solution

    function containsDuplicate($nums) {

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

    }
Copy after login

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;
    }
Copy after login

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!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template