[英]Invert Elements in ArrayList<Integer> Java
Ok so the point of this method is the invert the elements in an ArrayList of type . 好的,所以此方法的重点是反转类型为ArrayList的元素。 So if I have the elements:
因此,如果我有以下要素:
5 6 7 8 9 10 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 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. list是我的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? 输出为:10、9、8、9、10。有人可以向我解释为什么吗?
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-
10-9-8-7-6-5-4-3-2-1-
At the first iteration : temp = 1 / temp2 = 10
: we swap them 在第一次迭代中:
temp = 1 / temp2 = 10
:我们交换它们
At the second iteration : temp = 2 / temp2 = 9
: we swap them 在第二次迭代中:
temp = 2 / temp2 = 9
:我们交换它们
And we loop until we go through all the elem of the list which is the size of the list divided by 2. 然后循环,直到遍历列表的所有元素,即列表的大小除以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.
随意问的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.