Jak odwrócić tablicę int w Javie?
Próbuję odwrócić tablicę int w Javie.
Ta metoda nie odwraca tablicy.
for(int i = 0; i < validData.length; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
Co z nim nie tak? 30 answers
Aby odwrócić tablicę int, wymieniasz elementy aż do punktu środkowego, tak:
for(int i = 0; i < validData.length / 2; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
Sposób, w jaki to robisz, zamieniasz każdy element dwa razy, więc wynik jest taki sam, jak lista początkowa.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-31 21:46:44
Z Commons.Lang , można po prostu użyć
ArrayUtils.reverse(int[] array)
Przez większość czasu łatwiej i bezpieczniej jest trzymać się łatwo dostępnych bibliotek już przetestowanych i przetestowanych przez użytkownika, gdy zajmują się problemem.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-26 07:27:09
public class ArrayHandle {
public static Object[] reverse(Object[] arr) {
List<Object> list = Arrays.asList(arr);
Collections.reverse(list);
return list.toArray();
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-14 10:01:57
Myślę, że trochę łatwiej jest podążać za logiką algorytmu, jeśli deklarujesz jawne zmienne, aby śledzić indeksy, które wymieniasz przy każdej iteracji pętli.
public static void reverse(int[] data) {
for (int left = 0, right = data.length - 1; left < right; left++, right--) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
Myślę też, że bardziej czytelne jest robienie tego w pętli while.
public static void reverse(int[] data) {
int left = 0;
int right = data.length - 1;
while( left < right ) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
// move the left and right index pointers in toward the center
left++;
right--;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-19 14:58:05
Collections.reverse(Arrays.asList(yourArray));
java.util.Collections.reverse()
can reverse java.util.List
s and java.util.Arrays.asList()
zwraca listę, która zawija określoną tablicę, którą do niej przekazujesz, dlatego yourArray
jest odwrócona po wywołaniu Collections.reverse()
.
Koszt to tylko utworzenie jednego obiektu listy i nie są wymagane żadne dodatkowe biblioteki.
Podobne rozwiązanie zostało przedstawione w odpowiedzi Tarika i ich komentatorów, ale myślę, że ta odpowiedź byłaby bardziej zwięzła i łatwiejsza do przeanalizowania.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-08 08:57:14
Z Guawą:
Collections.reverse(Ints.asList(array));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-09 04:57:48
Jest tu już wiele odpowiedzi, głównie skupionych na modyfikacji tablicy w miejscu. Ale dla kompletności, oto inne podejście wykorzystujące strumienie Javy do zachowania oryginalnej tablicy i utworzenia nowej odwróconej tablicy:
int[] a = {8, 6, 7, 5, 3, 0, 9};
int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-13 09:37:37
Simple for loop!
for (int start = 0, end = array.length - 1; start <= end; start++, end--) {
int aux = array[start];
array[start]=array[end];
array[end]=aux;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-21 03:38:08
To ci pomoże.]}
int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
int temp = a[k];
a[k] = a[a.length-(1+k)];
a[a.length-(1+k)] = temp;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-13 04:16:44
Tak bym to osobiście rozwiązał. Powodem tworzenia parametryzowanej metody jest umożliwienie posortowania dowolnej tablicy... nie tylko twoje liczby całkowite.
Mam nadzieję, że coś z tego wyciągniesz.@Test
public void reverseTest(){
Integer[] ints = { 1, 2, 3, 4 };
Integer[] reversedInts = reverse(ints);
assert ints[0].equals(reversedInts[3]);
assert ints[1].equals(reversedInts[2]);
assert ints[2].equals(reversedInts[1]);
assert ints[3].equals(reversedInts[0]);
reverseInPlace(reversedInts);
assert ints[0].equals(reversedInts[0]);
}
@SuppressWarnings("unchecked")
private static <T> T[] reverse(T[] array) {
if (array == null) {
return (T[]) new ArrayList<T>().toArray();
}
List<T> copyOfArray = Arrays.asList(Arrays.copyOf(array, array.length));
Collections.reverse(copyOfArray);
return copyOfArray.toArray(array);
}
private static <T> T[] reverseInPlace(T[] array) {
if(array == null) {
// didn't want two unchecked suppressions
return reverse(array);
}
Collections.reverse(Arrays.asList(array));
return array;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-21 22:47:36
Najskuteczniejsze jest po prostu iteracja tablicy wstecz.
Nie jestem pewien, czy rozwiązanie Aarona robi to vi ten telefon Collections.reverse(list);
czy ktoś wie?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-26 06:21:29
Twój program będzie działał tylko dla length = 0, 1
.
Możesz spróbować:
int i = 0, j = validData.length-1 ;
while(i < j)
{
swap(validData, i++, j--); // code for swap not shown, but easy enough
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-26 19:44:19
Jeśli pracujesz z danymi bardziej prymitywnymi (np. char, byte, int, itp.), możesz wykonać kilka fajnych operacji XOR.
public static void reverseArray4(int[] array) {
int len = array.length;
for (int i = 0; i < len/2; i++) {
array[i] = array[i] ^ array[len - i - 1];
array[len - i - 1] = array[i] ^ array[len - i - 1];
array[i] = array[i] ^ array[len - i - 1];
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-13 00:04:20
for(int i=validData.length-1; i>=0; i--){
System.out.println(validData[i]);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-16 06:29:21
W przypadku Javy 8 możemy również użyć strumieni do odwrócenia tablicy liczb całkowitych jako:
int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
.toArray(); //Output: [5, 4, 3, 2, 1]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-15 14:52:22
public void display(){
String x[]=new String [5];
for(int i = 4 ; i > = 0 ; i-- ){//runs backwards
//i is the nums running backwards therefore its printing from
//highest element to the lowest(ie the back of the array to the front) as i decrements
System.out.println(x[i]);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-23 17:59:17
Oto proste, szybkie rozwiązanie. Mam nadzieję, że to pomoże!.
public int[] reverse(int[] arr) {
for(int i = arr.length; i > 0 ; i--){
System.out.print(arr[i-1] + " ");
}
return arr;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-13 00:05:27
public void getDSCSort(int[] data){
for (int left = 0, right = data.length - 1; left < right; left++, right--){
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-01 06:21:56
Czy zrobienie tego w ten sposób nie byłoby o wiele bardziej nieprawdopodobne dla błędów?
int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] temp = new int[intArray.length];
for(int i = intArray.length - 1; i > -1; i --){
temp[intArray.length - i -1] = intArray[i];
}
intArray = temp;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-04 05:58:15
Poniżej znajduje się kompletny program do uruchomienia w komputerze.
public class ReverseArray {
public static void main(String[] args) {
int arr[] = new int[] { 10,20,30,50,70 };
System.out.println("reversing an array:");
for(int i = 0; i < arr.length / 2; i++){
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Dla programów na macierzach wykorzystujących tablice będzie to dobre źródło .Przejdź przez link.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-14 11:55:32
Używając rozwiązania XOR aby uniknąć zmiennej temp Twój kod powinien wyglądać
for(int i = 0; i < validData.length; i++){
validData[i] = validData[i] ^ validData[validData.length - i - 1];
validData[validData.length - i - 1] = validData[i] ^ validData[validData.length - i - 1];
validData[i] = validData[i] ^ validData[validData.length - i - 1];
}
Zobacz ten link dla lepszego wyjaśnienia:
Http://betterexplained.com/articles/swap-two-variables-using-xor/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-27 18:50:41
Oto prosta implementacja, do odwrócenia tablicy dowolnego typu , plus pełne/częściowe wsparcie.
import java.util.logging.Logger;
public final class ArrayReverser {
private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());
private ArrayReverser () {
}
public static <T> void reverse(T[] seed) {
reverse(seed, 0, seed.length);
}
public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
if (seed == null || seed.length == 0) {
LOGGER.warning("Nothing to rotate");
}
int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
int end = Math.min(seed.length, endIndexExclusive) - 1;
while (start < end) {
swap(seed, start, end);
start++;
end--;
}
}
private static <T> void swap(T[] seed, int start, int end) {
T temp = seed[start];
seed[start] = seed[end];
seed[end] = temp;
}
}
Oto odpowiedni test jednostkowy
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
public class ArrayReverserTest {
private Integer[] seed;
@Before
public void doBeforeEachTestCase() {
this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}
@Test
public void wholeArrayReverse() {
ArrayReverser.<Integer>reverse(seed);
assertThat(seed[0], is(8));
}
@Test
public void partialArrayReverse() {
ArrayReverser.<Integer>reverse(seed, 1, 5);
assertThat(seed[1], is(5));
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-29 17:46:55
Rozwiązanie O(n) złożoności czasowej i o(1) złożoności przestrzeni.
void reverse(int[] array) {
int start = 0;
int end = array.length - 1;
while (start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-19 09:42:54
Oto co wymyśliłem:
// solution 1 - boiler plated
Integer[] original = {100, 200, 300, 400};
Integer[] reverse = new Integer[original.length];
int lastIdx = original.length -1;
int startIdx = 0;
for (int endIdx = lastIdx; endIdx >= 0; endIdx--, startIdx++)
reverse[startIdx] = original[endIdx];
System.out.printf("reverse form: %s", Arrays.toString(reverse));
// solution 2 - abstracted
// convert to list then use Collections static reverse()
List<Integer> l = Arrays.asList(original);
Collections.reverse(l);
System.out.printf("reverse form: %s", l);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-17 14:19:48
Istnieją dwa sposoby rozwiązania problemu:
1. Odwróć tablicę w przestrzeni.
Krok 1. Zamień elementy na początku i na końcu indeksu.
Krok 2. Zwiększ indeks początkowy zmniejsz indeks końcowy. Krok 3. Iteracja kroku 1 i Kroku 2 do indeksu początkowegoW tym przypadku złożoność czasu będzie O (n), A złożoność przestrzeni będzie O (1)
Przykładowy kod do odwrócenia tablicy w przestrzeni to like:
public static int[] reverseAnArrayInSpace(int[] array) {
int startIndex = 0;
int endIndex = array.length - 1;
while(startIndex < endIndex) {
int temp = array[endIndex];
array[endIndex] = array[startIndex];
array[startIndex] = temp;
startIndex++;
endIndex--;
}
return array;
}
2. Odwróć tablicę za pomocą tablicy pomocniczej.
Krok 1. Utwórz nową tablicę o rozmiarze równym podanej tablicy.
Krok 2. Wstawianie elementów do nowej tablicy począwszy od indeksu startowego, z podana tablica zaczyna się od indeksu końcowego.W tym przypadku złożoność czasu będzie O(n), A złożoność przestrzeni będzie O (N)
Przykładowy kod do odwrócenia tablicy z tablicą pomocniczą wygląda następująco:
public static int[] reverseAnArrayWithAuxiliaryArray(int[] array) {
int[] reversedArray = new int[array.length];
for(int index = 0; index < array.length; index++) {
reversedArray[index] = array[array.length - index -1];
}
return reversedArray;
}
Ponadto możemy użyć Collections API z Javy w tym celu.
Wewnętrznie API kolekcji używa tego samego podejścia odwrotnego w przestrzeni.
Przykładowy kod do korzystania z API kolekcji wygląda następująco:
public static Integer[] reverseAnArrayWithCollections(Integer[] array) {
List<Integer> arrayList = Arrays.asList(array);
Collections.reverse(arrayList);
return arrayList.toArray(array);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-23 22:09:56
static int[] reverseArray(int[] a) {
int ret[] = new int[a.length];
for(int i=0, j=a.length-1; i<a.length && j>=0; i++, j--)
ret[i] = a[j];
return ret;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-30 15:07:26
2 sposoby odwrócenia tablicy .
-
Używanie pętli For i zamiana elementów do punktu środkowego o złożoności czasowej O (n/2).
private static void reverseArray() { int[] array = new int[] { 1, 2, 3, 4, 5, 6 }; for (int i = 0; i < array.length / 2; i++) { int temp = array[i]; int index = array.length - i - 1; array[i] = array[index]; array[index] = temp; } System.out.println(Arrays.toString(array));
}
-
Używanie wbudowanej funkcji (zbiorów.reverse ())
private static void reverseArrayUsingBuiltInFun() { int[] array = new int[] { 1, 2, 3, 4, 5, 6 }; Collections.reverse(Ints.asList(array)); System.out.println(Arrays.toString(array));
}
Wyjście : [6, 5, 4, 3, 2, 1]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-18 13:19:28
public static int[] reverse(int[] array) {
int j = array.length-1;
// swap the values at the left and right indices //////
for(int i=0; i<=j; i++)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
j--;
}
return array;
}
public static void main(String []args){
int[] data = {1,2,3,4,5,6,7,8,9};
reverse(data);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-25 14:32:12
public static void main (String args[]){
//create array
String[] stuff ={"eggs","lasers","hats","pie","apples"};
//print out array
for(String x :stuff)
System.out.printf("%s ", x);
System.out.println();
//print out array in reverse order
for(int i=stuff.length-1; i >= 0; i--)
System.out.printf("%s ",stuff[i]);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-24 17:32:49
public class TryReverse {
public static void main(String[] args) {
int [] array = {2,3,4,5,6,7,8,9};
reverse(array);
for(int i=0; i<array.length; ++i)
System.out.print(array[i] + " ");
}
public static void reverse (int [] array){
for(int start=0, end=array.length-1; start<=end; start++, end--){
int aux = array[start];
array[start]=array[end];
array[end]=aux;
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-31 14:47:57