我试图将所有非零整数移动到数组的开头/左侧' a。'(例如{0,0,4,3,0}变为{4 ,3,0,0,0})
这是我的计划。它编译并运行没有错误,但数组最终只有零。任何建议将不胜感激。
int[] squeezeLeft(int[] a) {
int count = 0;
//creates new array
int [] a2 = new int[a.length];
//loops through a
for (int i = 0; i< a.length; i++){
//gets a temporary value from a[i]
int temp = a[i];
//assigns a[i] to temporary variable
a[count] = temp;
a[i] = 0;
/* raises count integer by one, so the following indice which is zero, is replaced
by the following non=zero integer*/
count++;
}
return a2;
}
答案 0 :(得分:1)
我知道这不是一个非常有效的解决方案O^2
,但它会按照你的要求行事。
private static int[] sequeezeLeft(final int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
for (int j = 0; j < a.length; j++) {
if (a[j] == 0) {
a[j] = a[i];
a[i] = 0;
}
}
}
}
return a;
}
O(n)
时间复杂度的另一个版本
private static int[] sqeeze2(int [] a){
int index = 0;
if(a.length == 0)
return a;
for(int i=0;i<a.length;i++){
if(a[i] !=0 && index < a.length){
a[index] = a[i];
a[i]=0;
index++;
}
}
return a;
}
答案 1 :(得分:1)
或者如果你有点懒,那么使用它呢?
Integer[] ints = new Integer[] { 0, 5, 2, 0, 1, 5, 6 };
List<Integer> list = Arrays.asList(ints);
Collections.sort(list);
Collections.reverse(list);
System.err.println(list); // prints [6, 5, 5, 2, 1, 0, 0]
不确定性能,但是..
答案 2 :(得分:1)
static void squeezeLeft(int[] array) {
int arrayIndex = 0;
if (array.length != 0) {//check the length of array whether it is zero or not
for (int i = 0; i < array.length; i++) {
if (array[i] != 0 && arrayIndex < array.length) {//check the non zero element of array
if (i != arrayIndex) {//if the index of non zero element not equal to array index
//only then swap the zero element and non zero element
array[arrayIndex] = array[i];
array[i] = 0;
}
arrayIndex++; //increase array index after finding non zero element
}
}
}
}
答案 3 :(得分:0)
与输入1,0,2,0,4,0,5,0,6,0
一样,第二个解决方案将失败,因为输出将是:
0245600000
对于o(n):
private static int[] reArrangeNonZeroElement(int arr[]) {
int count = 0;
if (arr.length == 0)
return arr;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
arr[count++] = arr[i];
}
}
for (; arr.length > count; ) {
arr[count++] = 0;
}
return arr;
}
答案 4 :(得分:0)
怎么样:
Arrays.sort(ints, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2)
{
if (o1 == 0) return 1;
if (o2 != 0 && o1 > o2) return 1;
if (o2 != 0 && o1 == o2) return 0;
return -1;
}
});