Facebook面试题 Moving positive, negative and zeros in an array
2017-01-10 10:54
501 查看
Given an input int array with positive, negative numbers and 0s. Putting negative number on the left side, zero in the middle and positive on the right side. Do it in
Analysis:
This question is very similar to Sorting Colors. We just need to keep 2 pointers for the last position of negative numbers and first place of positive numbers and put numbers to its corresponding position during traversal. Zeros will be in the middle automatically.
Java implementation is showed as following:
O(n)time and
O(1)space.
Analysis:
This question is very similar to Sorting Colors. We just need to keep 2 pointers for the last position of negative numbers and first place of positive numbers and put numbers to its corresponding position during traversal. Zeros will be in the middle automatically.
Java implementation is showed as following:
public class Solution { public void movingNumber(int[] nums) { if (nums == null || nums.length == 0) { return; } int start = 0; int end = nums.length - 1; for (int i = 0; i <= end; i++) { if (nums[i] < 0) { swap(nums, i, start); start++; } if (nums[i] > 0) { swap(nums, i, end); end--; i--; } } } private void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }
相关文章推荐
- Facebook面试题 find the peek or valley index in an array
- Distinguish between index of a decimal number and integer inside an array in Ruby?
- CareerCup Eliminate all ‘b’ and ‘ac’ in an array of characters
- Divide and Conquer:215. Kth Largest Element in an Array
- separate odd and even numbers in an array in O(n) time complexity and O(1) space complexity
- [week 16][Leetcode][Divide and Conquer] Kth Largest Element in an Array
- Divide and Conquer-215-Kth Largest Element in an Array
- An instance of getting the maximum and minimum values in an array
- Ruby: Count unique elements and their occurences in an array
- leetCode刷题归纳-Divide and Conquer(215. Kth Largest Element in an Array)
- Ruby: Count unique elements and their occurences in an array
- [JS Array]Find an item in an array that contains a string and then return that string
- Given an array of size N in which every number is between 1 and N, determine if there are any dupli
- leetcode_c++:Divide and Conquer:Kth Largest Element in an Array(215)
- You’re given an array containing both positive and negative integers and required to find the sub-a
- Rearrange an array of positive and negative integers
- 【算法】【Divide and conquer】Kth Largest Element in an Array
- 215. Kth Largest Element in an Array(divide and conquer)
- Divide and Conquer (1) -- Kth Largest Element in an Array,Different Ways to Add Parentheses
- how to remove nil and blank string in an array in Ruby