Leetcode基础刷题之PHP解析(342,344,349)

栏目: PHP · 发布时间: 6年前

题外话: 最近身体越来越差了,提醒各位:注意休息注意休息注意休息!!!。

2 0 1 9 - 4 -23   期三    

今天还是3题。

一篇   Leetcode基础刷题之 PHP 解析(292,303,326)

Leetcode基础刷题之PHP解析(342,344,349)

给个整数,判断是否是4的幂次方。

题目让我们不使用递归或者循环,我们先使用循环或者递归实现一遍。

/**
     * @param Integer $num
     * @return Boolean
     */
    function isPowerOfFour($num) {
          while($num && $num%4==0){
              $num =floor($num/4);
          }
          return $num==1;    
    }

想不循环和递归,那就需要找到规律,只要是4的幂次方的数,那么把它减去一之后都可以被3整除,调整一下就压榨成一行了。

/**
     * @param Integer $num
     * @return Boolean
     */
    function isPowerOfFour($num) {
        return $num>0 && !($num & ($num-1)) && ($num-1)%3==0;
    }

Leetcode基础刷题之PHP解析(342,344,349)

写一个函数反转数组中的字符串,要求是只能原地换,也就是说只能使用O(1)的空间复杂度.

/**
     * @param String[] $s
     * @return NULL
     */
    function reverseString(&$s) {
        $j=count($s)-1;
        for($i=0;$i<$j;$i++){
            $temp=$s[$i];
            $s[$i]=$s[$j];
            $s[$j]=$temp;
            $j--;
        }; 
        return $s;
    }

Leetcode基础刷题之PHP解析(342,344,349)

从两个数组中找出他们的交集。我这里直接把数组元素多的那个进行循环,每次比较元素少的那个数组,只要不同的直接删掉,最后因为交集是要唯一的,所以再去重。可以利用二分查找进行优化。

/**
     * @param Integer[] $nums1
     * @param Integer[] $nums2
     * @return Integer[]
     */
    function intersection($nums1, $nums2) {
        $big=count($nums1)>count($nums2)?$nums1:$nums2;
        $small=count($nums1)>count($nums2)?$nums2:$nums1;
        for($i=0;$i<count($big);$i++){
            if(!in_array($small[$i],$big)){
                unset($small[$i]);
            }
        }
        return array_unique($small);
    }

Github整理地址:https://github.com/wuqinqiang/leetcode-php


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

PHP and MySQL Web Development (3rd Edition) (Developer's Library

PHP and MySQL Web Development (3rd Edition) (Developer's Library

Luke Welling、Laura Thomson / Sams / 2004-09-29 / USD 49.99

We've taken the best and made it even better. The third edition of the best-selling PHP and MySQL Web Development has been updated to include material and code on MySQL 5, PHP 5 and on PHPs object mod......一起来看看 《PHP and MySQL Web Development (3rd Edition) (Developer's Library》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具