您的位置:首页 > 职场人生

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
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