lintcode(570)寻找丢失的数 II
来源:互联网 发布:cad三维绘图软件 编辑:程序博客网 时间:2024/06/06 00:12
描述:
给一个由 1 - n
的整数随机组成的一个字符串序列,其中丢失了一个整数,请找到它。
注意事项
n <= 30
样例:
给出 n = 20
, str = 19201234567891011121314151618
丢失的数是 17
,返回这个数。
思路:
难点在于字符串的分割,采用回溯的方式,如果出现不符合条件的情况,就返回到这一次操作的起始,如果执行到字符串最末,则返回分割结果
public class Solution { /** * @param n an integer * @param str a string with number from 1-n * in random order and miss one number * @return an integer */ public int findMissing2(int n, String str) { // Write your code here if( n < 1 || str == null ){ return 0; } int len = str.length(); int[] index = {0}; boolean[] exist = new boolean[n + 1]; search(n , str , index , exist , len); for(int i = 1;i<=len;i++){ if(!exist[i]){ return i; } } return 0; } public void search(int n , String str , int[] index , boolean[] exist , int len){ if(index[0] >= len){ return ; } if(str.charAt(index[0]) == '0'){ return ; } if(!exist[str.charAt(index[0]) - '0']){ exist[str.charAt(index[0]) - '0'] = true; index[0]++; search(n , str , index , exist , len); if(index[0] >= len){ return ; } index[0]--; exist[str.charAt(index[0]) - '0'] = false; } if(index[0] < len - 1){ int a = str.charAt(index[0]) - '0'; int b = str.charAt(index[0] + 1) - '0'; int value = 10*a + b; if(value <= n && !exist[value]){ exist[value] = true; index[0] += 2; search(n , str , index , exist , len); if(index[0] >= len){ return ; } index[0] -= 2; exist[value] = false; } } }}
0 0
- lintcode(570)寻找丢失的数 II
- 寻找丢失的数 II-LintCode
- 寻找丢失的数
- LintCode-寻找缺失的数
- LintCode 寻找缺失的数
- 寻找缺失的数-LintCode
- LintCode 寻找缺失的数
- LintCode -- 寻找缺失的数
- lintcode ----寻找缺失的数
- lintcode --寻找缺失的数
- 寻找缺失的数-LintCode
- LintCode 寻找缺失的数
- 寻找重复的数-LintCode
- 寻找丢失的三个数
- 寻找连续数中丢失的数
- LintCode-落单的数 II
- lintcode-落单的数 II
- LintCode 落单的数 II
- 大小端存储
- java字符串左移或右移几位(三次反转思想)
- javascript正则学习(二)
- 前端库API------必学
- Mr.Smile填坑记——Unity 3D直接将游戏运行到安卓手机上
- lintcode(570)寻找丢失的数 II
- linux给角色赋予操作文件的权限
- python中带星号/一个星号/两个星号的参数
- 动软代码生成器连接oracle数据库
- 手写简单瀑布流
- 手机连接电脑不读手机的终极解决方案
- 精通MongoDB数据库
- React 之 组件与组件抽离
- 相对定位与绝对定位