Love丶FFC's Blog

LintCode_naive:交换数组两个元素

2019-08-18 16:36:57
阅读:510   •   评论:2
标签:,

描述

给你一个数组和两个索引,交换下标为这两个索引的数字

样例

样例1

输入:  [1, 2, 3, 4], index1 = 2, index2 = 3
输出:  交换后你的数组应该是[1, 2, 4, 3], 不需要返回任何值,只要就地对数组进行交换即可。
样例解释: 就地交换,不需要返回值。

样例2

输入:  [1, 2, 2, 2], index1 = 0, index2 = 3
输出: 交换后你的数组应该是[2, 2, 2, 1], 不需要返回任何值,只要就地对数组进行交换即可。	
样例解释: 就地交换,不需要返回值。

编程语言:Java

解题思想:

1.交换两个元素即可。

时间复杂度:O(1)

IDE代码如下:

  1. package Lintcode;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Scanner;
  5.  
  6. public class _484 {
  7.  
  8. public static void main(String[] args) {
  9. int[] Number = new int[] {2,4,9,8};
  10. Scanner scanner = new Scanner(System.in);
  11. int index1 = scanner.nextInt();
  12. int index2 = scanner.nextInt();
  13. int swap;
  14. swap=Number[index1];
  15. Number[index1]=Number[index2];
  16. Number[index2]=swap;
  17. System.out.println(Arrays.toString(Number));
  18. }
  19. }
  20.  

LintCode编辑器代码如下:

  1. public class Solution {
  2. /**
  3.   * @param A: An integer array
  4.   * @param index1: the first index
  5.   * @param index2: the second index
  6.   * @return: nothing
  7.   */
  8. public void swapIntegers(int[] A, int index1, int index2) {
  9. int swap;
  10. swap=A[index1];
  11. A[index1]=A[index2];
  12. A[index2]=swap;
  13. }
  14. }

评论板

共有 2 条评论

  1. Gealpaste

    One major sign for me was EXTREME thirst cialis vs viagra

  2. intuido

    There were no recent changes in her medication and diet buy cialis online using paypal Physicians for a National Health Program PNHP has submitted the following question Do you support a single payer health program, aka improved Medicare for all

--------查看该分类下最新文章--------
^
新版博客正在完善中!域名:http://www.loveffc:8080,点击跳转,完全移植后将去除端口号。

Copyright © 2018 - 2021 FFC的小站 - 滇 ICP 备 18010780 号 - 1

- Powered by WordPress & AliYun · Theme by FFC -

- Environment by Windows & XAMPP · Designed by WebStorm & VSCode -

已运行:

访问量:489207