LeetCode刷题系列(十六)Some Little Questions
2016-07-06 20:11
489 查看
本篇给出了几道并没有太多技巧的的小问题。
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]; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解