题目:

来源:https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&&tqId=11203&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述 在一个长度为n的数组里的所有数字都在0到n-1的范围内。数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中一个重复的数字。例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是一个重复的数字2

Java

    public int findRepeatNumber(int[] nums) {Set<Integer> set = new HashSet<>();for (int num : nums) {if (!set.add(num))return num;}return -1;}

C++

class Solution {
public:int findRepeatNumber(vector<int>& nums) {unordered_map<int, bool> map;for(int num : nums) {if(map[num]) return num;map[num] = true;}return -1;}
};

JS

/*** @param {number[]} nums* @return {number}*/
var findRepeatNumber = function(nums) {let s=new Set();for(var i in nums){var Length=s.size;s.add(nums[i]);if(s.size==Length)return nums[i];}
};

Python

class Solution(object):def findRepeatNumber(self, nums):""":type nums: List[int]:rtype: int"""dic = {}for i in nums:if i not in dic:dic[i] = 0else:return i

新题目:

在一个长度为n的数组里的所有数字都在0到n-1的范围内。数组中没有数字是重复的, 例如,如果输入长度为7的数组{2,1,3,0,4},那么把该数组重新排好序。要求不能使用语言自带的排序算法,要求空间复杂度为O(1)。

题目思路

  • 数组中的元素值是2、1、3、0、4,同时数组的索引下标是0、1、2、3、4

  • 可以发现数组的元素的索引和数组值存在一一对应的关系

  • 因此可以通过遍历数组,比如某第一个元素值2索引是0,我们做一个交换,就把它放到nums[2]中(也就是到把第一个元素值2放到了索引是2的地方,即nums[current] = current),这样把数组的值和索引一一对应起来。

新题目图解思路

动画视频:

新题目复杂度

动画视频

代码实现

Java

class Solution {public int findRepeatNumber(int[] nums) {for(int current = 0;current < nums.length;) {if (nums[current] == current) {current++;} else {// 当前index = current下标值nums[current]和 index = nums[current] 的下标值 nums[nums[current]]相等if(nums[current] == nums[nums[current]]) {return nums[current];} else {swapTwoNumberInArray(nums, current, nums[current]);}}}return -1; // 没找到}public  void swapTwoNumberInArray(int[] nums, int current, int another) {int temp = nums[current];nums[current] = nums[another];nums[another] = temp;}
}

C++

class Solution {
public:int findRepeatNumber(vector<int>& nums) {for(int i = 0; i < nums.size(); ++i){while(nums[i] != i)     //当前元素不等于下标{if(nums[i] == nums[nums[i]])    return nums[i];swap(nums[i],nums[nums[i]]);            }}   return -1;}
};

Python

class Solution(object):def findRepeatNumber(self, nums):""":type nums: List[int]:rtype: int"""for i in range(len(nums)):while nums[i] != i:if nums[nums[i]] == nums[i]:return nums[i]nums[nums[i]] , nums[i] = nums[i] , nums[nums[i]] # 交换return None

JS

var findRepeatNumber = function(nums) {const length = nums.length;for (let i = 0; i < length; ++i) {// 检测下标为i的元素是否放在了位置i上while ((num = nums[i]) !== i) {if (num === nums[num]) {return num;}[nums[i], nums[num]] = [nums[num], nums[i]]; // 交换}}
};

小夕的牛客网Java代码

public class Solution {// Parameters://    numbers:     an array of integers//    length:      the length of array numbers//    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;//                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++//    这里要特别注意~返回任意重复的一个,赋值duplication[0]// Return value:       true if the input is valid, and there are some duplications in the array number//                     otherwise falsepublic  boolean duplicate(int numbers[],int length,int [] duplication) {if(numbers == null) {return false;}if(findRepeatNumber(numbers) != -1){duplication[0] = findRepeatNumber(numbers);return true;}return false;}public  int findRepeatNumber(int[] nums) {for(int current = 0;current < nums.length;) {// num[current] = current 说明归位了 也就是成为了有序数组,那么继续往下遍历。if (nums[current] == current) {current++;} else {// 当前index = current下标值nums[current]和 index = nums[current] 的下标值 nums[nums[current]]相等// 找到重复数字了if(nums[current] == nums[nums[current]]) {return nums[current];} else {// 没找到重复数字 所以把这两个数组中的数进行交换// 目的是为了让num[current] = current 这样就变成了有序数组swapTwoNumberInArray(nums, current, nums[current]);}}}return -1; // 没找到}public  void swapTwoNumberInArray(int[] nums, int current, int another) {int temp = nums[current];nums[current] = nums[another];nums[another] = temp;}
}

第一个数字的思路

  • 还是复用之前的思路,把数字依次归位

  • 当找到重复的数字的时候,不直接返回,而是用set把所有的重复数字保留下来。

  • 然后遍历数组,找到这些重复数字的下标,然后把下标最小的那个数字返回,就得到了第一个了

第一个数字AC的牛客网Java代码

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Solution {// Parameters://    numbers:     an array of integers//    length:      the length of array numbers//    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;//                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++//    这里要特别注意~返回任意重复的一个,赋值duplication[0]// Return value:       true if the input is valid, and there are some duplications in the array number//                     otherwise falsepublic  boolean duplicate(int numbers[],int length,int [] duplication) {if(numbers == null) {return false;}Set<Integer> repeatNumberSet = new HashSet<>();Map<Integer, Integer> repeatNumberMap =  new HashMap<>();getMap(numbers, repeatNumberMap);findRepeatNumber(numbers, repeatNumberSet);if(repeatNumberSet.size() != 0){duplication[0] = getFirstNumber(numbers, repeatNumberSet, repeatNumberMap );return true;}return false;}public  int findRepeatNumber(int[] nums, Set<Integer> repeatNumberSet) {for(int current = 0;current < nums.length;) {// num[current] = current 说明归位了 也就是成为了有序数组,那么继续往下遍历。if (nums[current] == current) {current++;} else {// 当前index = current下标值nums[current]和 index = nums[current] 的下标值 nums[nums[current]]相等// 找到重复数字了if(nums[current] == nums[nums[current]]) {repeatNumberSet.add(nums[current]);current++;
//                    return nums[current];} else {// 没找到重复数字 所以把这两个数组中的数进行交换// 目的是为了让num[current] = current 这样就变成了有序数组swapTwoNumberInArray(nums, current, nums[current]);}}}return -1; // 没找到}public  void swapTwoNumberInArray(int[] nums, int current, int another) {int temp = nums[current];nums[current] = nums[another];nums[another] = temp;}public  void getMap(int[] nums,  Map<Integer, Integer> repeatNumberMap) {for(int i = 0;i < nums.length; i++) {Set<Integer> keySet = repeatNumberMap.keySet();if (keySet != null && keySet.contains(nums[i])) {if (repeatNumberMap.get(nums[i]) > i) {repeatNumberMap.put(nums[i],i);}} else {repeatNumberMap.put(nums[i],i);}}}public  int getFirstNumber(int[] nums, Set<Integer> repeatNumberSet, Map<Integer, Integer> repeatNumberMap) {int minIndex = nums.length;int min = -1;for(Integer repeatNumber : repeatNumberSet ) {if (repeatNumberMap.get(repeatNumber) < minIndex) {minIndex = repeatNumberMap.get(repeatNumber);min = repeatNumber;}}return min;}
}

一道不起眼的面试题,但被头条面试官玩出了花,48张图,2个动画,带你还原面试现场相关推荐

  1. 我去头条面试,面试官问我如何设计好API,看看我是如何吊打面试官的!

    作者 | 点击关注 ???? 来源 | Java开发宝典(ID:javakaifabaodian) 头图 | CSDN 下载自东方 IC "语言首先是写给人看的,只是恰巧(incidenta ...

  2. 99%的面试官都会问到的Java面试题

    转载自  99%的面试官都会问到的Java面试题 最近是招聘季,所谓金九银十,正是跳槽的好几节.今天,给大家整理了一些Java面试常考的经典题目,我们一道一道来分析一下. 经典面试题 1.谈谈你对 J ...

  3. 面试官:你对Redis缓存了解吗?面对这11道面试题是否有很多问号?

    关于Redis的知识总结了一个脑图分享给大家 1.在项目中缓存是如何使用的?为什么要用缓存?缓存使用不当会造成什么后果? 面试官心理分析 这个问题,互联网公司必问,要是一个人连缓存都不太清楚,那确实比 ...

  4. 面试官:你对Redis缓存了解吗?面对这11道面试题你是否有很多问号?

    前言 关于Redis的知识,总结了一个脑图分享给大家 1.在项目中缓存是如何使用的?为什么要用缓存?缓存使用不当会造成什么后果? 面试官心理分析 这个问题,互联网公司必问,要是一个人连缓存都不太清楚, ...

  5. 2020最新大厂(阿里头条百度快手美团滴滴猿辅导陌陌)Java开发岗位社招面试干货分享总结

    (尊重劳动成果,转载请注明出处:https://yangwenqiang.blog.csdn.net/article/details/106033403 冷血之心的博客) 前言: 按照惯例,我先来个自 ...

  6. 阿里发布内部(面试官)题库:2022年Java社招岗(正式版)面试题

    阿里巴巴2022年Java架构师岗面试题(正式版) 这不马上就是金三银四的面试跳槽季了嘛,马士兵老师也是通过一些小手段为大家拿到了一份阿里巴巴2022年Java架构师岗面试题(正式版)现在分享给大家, ...

  7. 阿里面试官内部题库,阿里发布2022年Java岗(正式版)面试题

    阿里巴巴2022年Java架构师岗面试题(正式版) 这不马上就是金三银四的面试跳槽季了嘛,小编也是通过一些小手段为大家拿到了一份阿里巴巴2022年Java架构师岗面试题(正式版)现在分享给大家,这份资 ...

  8. 88道BAT Java面试题 助你跳槽BAT,轻松应对面试官的灵魂拷问

    88道BAT Java面试题 助你跳槽BAT,轻松应对面试官的灵魂拷问 前言: 备战金九银十逃脱不了面试官的灵魂拷问,笔者整理了88道Java面试,由于面试题太多文章没有包含答案,需要领取这些面试题答 ...

  9. 4张图,带你看透今日头条人工智能。

    IT派 - {技术青年圈} 持续关注互联网.大数据.人工智能领域 关注 往期 精彩回顾 重大改变!Excel即将接入Python!办公软件也要革命 2017年大数据领域薪资有多高? 女博士实名举报长江 ...

  10. 漫画:美团面试题(面试时,面试官给了我一块巧克力。。)

    今天是小浩算法"365刷题计划"第76天.这次小浩又出去面试,虽然面试官没让他修电暖气,但却给了他一块巧克力...(题目由读者在美团面试后提供) 01 PART 巧克力 巧克力的凹 ...

最新文章

  1. imp 只导表前10条数据_Excel数据规范化10条原则,让你的工作效率快速提升
  2. httpclient3.1的多线程处理
  3. 创建oracle实例
  4. java的定时器用法
  5. mysql优化之sakila测试数据库
  6. 分析数据时,一定要避开这5大误区!
  7. Java集合框架(3)
  8. leetcode574. 当选者(SQL)
  9. 数论基础知识点整理(基础篇)
  10. SAS安装时出现的问题:Diagram Control
  11. java的hashmap排序_java 中HashMap排序
  12. cdr 表格自动填充文字_Excel表格设置生成自动填充序号、编号
  13. Android消息机制和应用
  14. Word文档进行XXE攻击
  15. 20190325 Django自定义过滤器和自定义模板标签
  16. Win10下通过源码编译安装QGIS
  17. 儿童在未来游戏中的监管与保护趋势
  18. win7和linux下的文件共享
  19. Oracle 全文索引
  20. 非淡泊无以明志, 非宁静无以致远

热门文章

  1. 【leetcode】遍历二叉树从跟到叶子的核心代码
  2. Quartz cron 表达式格式
  3. 嵌入Windows User Control到ASP.NET web form
  4. JS--我发现,原来你是这样的JS:面向对象编程OOP[1]--(理解对象和对象属性类型)...
  5. Xamarin iOS教程之视图显示图像
  6. 收集一些关于视频文件格式以及编码计算的一些知识
  7. [解答]对‘’未定义的引用 collect2: 错误: ld 返回 1
  8. python - PyDev统一编码
  9. KingDZ 变菜鸟,每日一个C#小实例之---玩转鼠标
  10. XNA中的中文输入(一)