不知道这是否重复,但这是一个问我的面试问题。给定一个随机数组和-1放在中间,我必须压缩数组意味着要替换所有-1s,最终输出应该是带有新数组的最后一个有效索引。例如。
Input:
3 4 -1 -1 -1 5 8 -1 8
Output:
3 4 5 8 8 5 8 -1 8 and last valid index is 4
Input:
-1 -1 -1 -1 -1 2
Output:
2 -1 -1 -1 -1 2 and last valid index is 0
Input:
-1 -1 -1 3 3 3
Output:
3 3 3 3 3 3 and last valid index is 2
你不应该交换值,只是最后一个有效索引和数组足以解密非-1值。
答案 0 :(得分:7)
int K=0
FOR i=0; i<LEN; i++
IF arr[i]!=-1
arr[K]=arr[i]
K++
END IF
RETURN K-1
答案 1 :(得分:2)
那样的东西?这是PHP
<?php
$array = array('3','4','-1','-1','-1','5','8','-1','8');
$count = count($array);
$k = 0;
$i = 0;
while($i < $count && $k < $count)
{
echo $array[$i];
if($array[$i] == '-1')
{
echo '|';
if ($i>=$k){$k = $i + 1;}
$found = false;
while($k < $count && !$found)
{
echo 'X';
if($array[$k] != '-1')
{
$array[$i] = $array[$k];
$found = true;
}
$k++;
}
}
$i++;
}
print_r($array);
echo 'Last index'.($i - 1);
?>
答案 2 :(得分:1)
import java.util.Arrays;
public class Compact {
static int previousValid(int[] nums, int startIndex) {
while (--startIndex >= 0 && nums[startIndex] == -1);
return startIndex;
}
static int nextInvalid(int[] nums, int startIndex) {
while (++startIndex < nums.length && nums[startIndex] != -1);
return startIndex;
}
static void compact(int... nums) {
int last = previousValid(nums, nums.length);
for (int h = -1, t = last + 1;
(h = nextInvalid(nums, h)) < (t = previousValid(nums, t));
) {
nums[last = h] = nums[t];
}
System.out.println(Arrays.toString(nums) + "; last valid = " + last);
}
public static void main(String[] args) {
compact(3, 4, -1, -1, -1, 5, 8, -1, 8);
// "[3, 4, 8, 8, 5, 5, 8, -1, 8]; last valid = 4"
compact(-1, -1, -1, -1, -1, 2);
// "[2, -1, -1, -1, -1, 2]; last valid = 0"
compact(-1, -1, -1, 3, 3, 3);
// "[3, 3, 3, 3, 3, 3]; last valid = 2"
compact(-1, -1, -1);
// "[-1, -1, -1]; last valid = -1"
compact(6, 6, 6);
// "[6, 6, 6]; last valid = 2"
}
}
主要观点:
previousValid
和nextInvalid
辅助方法使逻辑更清晰h
和t
代表“head”和“tail”
h
找到nextInvalid
t
找到previousValid
nums
t
从索引h
分配到h < t