Arrays 压缩给定阵列问题
我不知道这是否是重复的,但这是一个面试时问我的问题。给定一个随机数数组,中间放置-1,我必须压缩数组,这意味着所有的-1都将被替换,最终输出应该是新数组的最后一个有效索引。比如说Arrays 压缩给定阵列问题,arrays,Arrays,我不知道这是否是重复的,但这是一个面试时问我的问题。给定一个随机数数组,中间放置-1,我必须压缩数组,这意味着所有的-1都将被替换,最终输出应该是新数组的最后一个有效索引。比如说 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 In
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
您不应该交换值,只要最后一个有效索引与数组一起就足以破译not-1值。类似的内容?它是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);
?>
导入java.util.array;
公共类契约{
静态int-previousValid(int[]nums,int-startIndex){
而(-startIndex>=0&&nums[startIndex]=-1);
返回startIndex;
}
静态int nextInvalid(int[]nums,int startIndex){
而(++startIndex
关键思想:
- 使用
和previousValid
helper方法使逻辑更清晰nextInvalid
- 跟踪“头”和“尾”的
和h
t
查找h
nextInvalid
查找以前有效的t
- 当
h
int K=0
对于i=0;iClassy实现。虽然在循环中使用循环,但顺序仍应为n。我说得对吗?@Bragaadesh:是的,这仍然是O(N)
。循环中的循环本身并不意味着它是O(N^2)
@bragaadesh:我刚刚意识到这是一种不同于您最初想要的压缩,[3,4,8,8,5…]
而不是[3,4,5,8,8…]
。请参阅下面tijoy27的答案,以获得更好的答案=)
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"
}
}
int K=0
FOR i=0; i<LEN; i++
IF arr[i]!=-1
arr[K]=arr[i]
K++
END IF
RETURN K-1