zoukankan      html  css  js  c++  java
  • 数组和矩阵(1)——Find the Duplicate Number

    Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

    Note:

    1. You must not modify the array (assume the array is read only).  //不能排序
    2. You must use only constant, O(1) extra space.                         // 不能用哈希表
    3. Your runtime complexity should be less than O(n2).                  //不能暴力求解
    4. There is only one duplicate number in the array, but it could be repeated more than once.

    https://segmentfault.com/a/1190000003817671#articleHeader4

    考虑:

    1. 暴力求解,选择一个数,看有没有重复的;
    2. 哈希表
    3. 排序后遍历
    4. 二分法
    5. 设置快慢指针,映射找环法
     1 public class Solution {
     2     public int findDuplicate(int[] nums) { //映射找环
     3         int n = nums.length - 1;
     4         int pre = 0;
     5         int last = 0;
     6         do {
     7             pre = nums[pre];
     8             last = nums[nums[last]];
     9         } while(nums[pre] != nums[last]);
    10         last = 0;
    11         while(nums[pre] != nums[last]) {
    12             pre = nums[pre];
    13             last = nums[last];
    14         }
    15         return nums[last];
    16     }
    17 }
  • 相关阅读:
    Jmeter之检查点
    Jmeter之集合点
    Jmeter之参数化
    Jmeter组件认识
    Jmeter目录认识
    sts的web工程创建
    Jmeter的BeanShell脚本开发
    Jmeter插件开发
    Appium配置app老是反复安装问题的处理
    eclipse通过git代码的下载和上传
  • 原文地址:https://www.cnblogs.com/-1307/p/6905979.html
Copyright © 2011-2022 走看看