简体   繁体   中英

Invert Elements in ArrayList<Integer> Java

Ok so the point of this method is the invert the elements in an ArrayList of type . So if I have the elements:

5 6 7 8 9 10

once I call the method, the position of the elements should be Inverted as such:

10 9 8 7 6 5

This is the method, any advice would be greatly appreciated :).

public void invertElements()
    {
        for (int i = list.size()-1; i <= -1; i--)
        {
            int temp = list.get(i);
            for(int j = 0; j < list.size()-1; j++)
            {
            list.set(j, temp);
            }

        }
    }

list is the name of my ArrayList.

Update: Just tried this way:

public void invertElements()
    {
        int index = 0;
        for (int i = list.size()-1; i > -1; i--)
        {
            int temp = list.get(i);
            list.set(index, temp);
            index++;
            if(index == list.size()-1)
            {
                break;
            }

        }
    }

which gives the output: 10, 9, 8, 9, 10 Could someone explain to me why?

You can take the extremities of the list at each iteration and swap them :

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
    for (int i = 0; i < list.size()/2; i++){
                int temp = list.get(i);
                int temp2 = list.get(list.size()-1-i);
                list.set(i, temp2);
                list.set(list.size()-1-i, temp);
      }
        for(Integer i : list)
            System.out.print(i+"-");

Gives the output :

10-9-8-7-6-5-4-3-2-1-

At the first iteration : temp = 1 / temp2 = 10 : we swap them
At the second iteration : temp = 2 / temp2 = 9 : we swap them

And we loop until we go through all the elem of the list which is the size of the list divided by 2.

Solution is

public void invertElems(List<Integer> list) {
  for (int i = 0; i < list.size() / 2; ++i) { // we only need iterating half of the size of list
    int elem = list.get(i); // we store element in additional variable
    list.set(i, list.get(list.size() - i - 1)); // we set i-th elementh with i-th element from the back
    list.set(list.size() - i - 1, elem);
  }
}

Linear time. Feel free to ask questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM