leetcode -- 442. Find All Duplicates in an Array 【数组随机性 + 数据特点 + 整数符号位使用】
2017-07-03 22:27
267 查看
题目
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appeartwice and others appearonce.Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
题意
给定一个整型数组,整型数组中的元素范围为 1 <= a[ i ] <= n ,一些元素出现了两次,一些出现了一次。找出所有出现两次的元素。分析及解答
解法1:
【两个限制】 (1)整型范围,因为整型范围较小,所以我们可以借助数组能够随机访问的优势;(2)出现次数,出现次数是固定的数字,所以我们可以简化重复的判断的条件。【缺陷】未能在不借助辅助空间的情况下实现该算法。
public class Solution { public List<Integer> findDuplicates(int[] nums) { List<Integer> duplicates = new LinkedList<>(); int[] results = new int[nums.length + 1 ]; for(int num : nums){ results[num]++; } for(int i = 1; i < results.length;i++){ if(results[i] == 2){ duplicates.add(i); } } return duplicates; } }
解法2:(利用限制)
【巧妙利用限制】前面提到了两个限制,解法2 利用出现的数字均为正整数这个限制,利用其作为一次计数的标志。因为是正整数,所以我们符号位便没有充分利用起来,另外因为每个数字最多出现两次,所以我们可以将负号作为标志,记作一次计数。于是就得到了下面的做法。【局限】该解法与题目耦合性很强,不具有普适性。
public class Solution { // when find a number i, flip the number at position i-1 to negative. // if the number at position i-1 is already negative, i is the number that occurs twice. public List<Integer> findDuplicates(int[] nums) { List<Integer> res = new ArrayList<>(); for (int i = 0; i < nums.length; ++i) { int index = Math.abs(nums[i])-1; if (nums[index] < 0) res.add(Math.abs(index+1)); nums[index] = -nums[index]; } return res; } }
相关文章推荐
- (2)int A[nSize],其中隐藏着若干0,其余非0整数,写一个函数int Func(int* A, int nSize),使A把0移至后面,非0整数移至数组前面并保持有序,返回值为原数据中第一个元素为0的下标。(尽可能不使用辅助空间且考虑效率及异常问题,注释规范且给出设计思路)
- LeetCode 两个整数的加法运算,不使用+符号
- 数据类型和抽象数据类型是如何定义的。二者有何相同和不同之处,抽象数据类型的主要特点是什么?使用抽象数据类型的主要好处是什么?
- 使用ASP.NET AJAX异步调用Web Service和页面中的类方法(8):服务器端和客户端数据类型的自动转换:数组类型
- Common Subsequence 动态规划 不难 但是犯了个错误刚开始 没用标记数组 直接使用a判断 是否为零 结果是测试数据有很多key为零 超时
- [小算法] 使用递归将一个整数逆序放入一数组中
- 学生类封装 , (链表)插入排序成绩 无动态数组 ,动态开辟空间 以及静态函数,数据成员的使用
- 使用数组实现快速数据查找
- [C] 跨平台使用Intrinsic函数范例3——使用MMX、SSE2指令集 处理 32位整数数组求和
- Fortran 从文件中读取数据放入数组中,然后对其进行bubble sort,使用了一些方法防止人为错误
- 如何通过 Visual C# 使 Excel 自动执行操作以使用数组来填充或获取某区域中的数据
- AJAX保存数据时,如果参数中有&符号时,使用escape关键字处理
- 新手入门:Java数组特点及基本使用技巧
- asp下使用数组存放数据的代码
- 关于int型整数按逆序存入数组中的问题(也即十进制数和其他类型数据的转换问题)
- 使用数组作为数据成员来实现栈
- Java数组特点及基本使用技巧
- 从键盘输入20个整数将奇数&偶数分别存在不同的数组中并按先奇数后偶数的顺序输出这两个数组中的数据
- 使用存储过程实现循环更新3组数组中的数据
- 使用递归函数,查询数据表将子类ID(包括孙类ID,重孙类ID...)保存为数组