LeetCode刷题系列(十六)Some Little Questions
来源:互联网 发布:海奇软件app 编辑:程序博客网 时间:2024/06/07 10:39
本篇给出了几道并没有太多技巧的的小问题。
Reverse Words in a String
这道题倒转一个字符串中所有的单词。
public String reverseWords(String s) { if (s == null || s.length() == 0) { return ""; } String[] array = s.split(" "); StringBuilder sb = new StringBuilder(); for (int i = array.length - 1; i >= 0; --i) { if (!array[i].equals("")) { sb.append(array[i]).append(" "); } } //remove the last " " return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);}
Partition Array
这道题为划分数组。将数组中小于k的数移到左边,大于等于k的数移到右边。这道题也借助了两个指针的方法。
public int partitionArray(int[] nums, int k) { //write your code here if(nums == null || nums.length == 0){ return 0; } // //dummy number // nums.add(k); int i = 0; int j = nums.length - 1; for(; i <= j; i++){ if(nums[i]< k){ continue; } while(j >= i && nums[j] >= k){ j --; }//while //i points to a number >= k //j points to a number < k //swap i and j if(j >= 0 && i < j){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; j --; } }//for // nums.remove(j + 1); return j + 1;}
Interleaving Positive and Negative Numbers
这道题为交错正负数。将正数和负数互相交叉,需要注意的是数量多的放在前面,如果正数多则第一个数为正数。我们使用两个数组分别挑出正数和负数,然后交错放在原数组里。
public int[] subfun(int[] A,int [] B, int len) { int[] ans = new int[len]; for(int i = 0; i * 2 + 1 < len; i++) { ans[i * 2] = A[i]; ans[i * 2 + 1] = B[i]; } if(len % 2 == 1) ans[len - 1] = A[len / 2]; return ans;}public void rerange(int[] A) { int[] Ap = new int[A.length]; int totp = 0; int totm = 0; int[] Am = new int[A.length]; int[] tmp = new int[A.length]; for(int i = 0; i < A.length; i++) if(A[i] > 0) { Ap[totp] = A[i]; totp += 1; } else { Am[totm] = A[i]; totm += 1; } if(totp > totm) tmp = subfun(Ap, Am, A.length); else tmp = subfun(Am, Ap, A.length); for (int i = 0; i < tmp.length; ++i) A[i] = tmp[i];}
0 0
- LeetCode刷题系列(十六)Some Little Questions
- LeetCode刷题系列(十二)Quick Questions
- leetcode Some questions of Edit Distance
- some questions
- Some questions
- Discovers some questions
- Some MySql Questions
- Some other questions
- Some questions about ConcurrentLinkedQueue
- some C++ questions
- Gas Station——Leetcode系列(十六)
- some little trick
- Some Little Thing
- Some Little Tips
- some little software
- Some Questions about eXtremeDB Log
- Some questions about RT-preempt
- Some questions about ambient noise
- Linux开发工具(gcc gdb make shell)——c的预处理、编译、汇编和链接
- c++面向对象编程补充(一) 重载 覆盖 隐藏区别
- java注释规范
- 【树的重心】 POJ 1655 Balancing Act
- HDU 1829 A Bug's Life(基础种类并查集)
- LeetCode刷题系列(十六)Some Little Questions
- 日本国立国会图书馆书籍批量下载(一)
- java新手学习之开发教程
- Leetcode刷题系列(十七)Graph相关
- java语言编程简介
- Leetcode刷题系列(十八)CombinationSum && WordLadder
- 编译的细分————
- 万能Host google
- Spark 应用程序调优