在数组中获取与索引相反的元素的最佳方法是什么?

时间:2013-08-01 15:23:09

标签: algorithm

说我有阵列

{0, 1, 2, 3, 4}
  • 索引0和4是对立的
  • 索引1和3是对立的
  • 索引2的反面是未定义的

 {0, 1, 2, 3, 4, 5}
  • 索引0和5是对立的
  • 索引1和4是对立的
  • 索引2和3是对立的

我记得有一种非常聪明的方法可以做到这一点。像

这样的东西
i%array.length 

3 个答案:

答案 0 :(得分:4)

试试这个:

oppIndex = array.length - firstIndex - 1;

答案 1 :(得分:1)

array = {1, 2, 3, 4, 5}
idx = 0 /* 0 is the first array position with value of 1 */

IF array.length - idx - 1 > idx
   RETURN array[ array.length - idx - 1 ] /* returns array[4] == 5 */
ELSE
   RETURN undefined

array = {1, 2, 3, 4, 5}
idx = 2 /* 2 is the third array position with value of 3 */

IF array.length - idx - 1 > idx /* 5 - 2 - 1 == 2 which is NOT greater than 2 */
   RETURN array[ array.length - idx - 1 ]
ELSE
   RETURN undefined

答案 2 :(得分:0)

按照你的第一个逻辑示例......

       if (array.length%2==0){
            for (int i =0; i<array.length/2; i++){
                   syso("the opposite of "+ array[i] + " is " + array[array.length -1-i]
             }
       }
       else {
           for (int i =0; i<floor(array.length/2); i++){
                   syso("the opposite of "+ array[i] + " is " + array[array.length -1-i]
             }
             i = i+1
              syso("the opposite of "+ array[i] +" is undefined"
       }