LintCode: Swap Two Integers in Array

Swap Two Integers in Array



Similar Problems:


Given an integer array of size n, find all elements that appear more than n/3 times. The algorithm should run in linear time and in O(1) space.

Github: code.dennyzhang.com

Credits To: lintcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// Blog link: https://code.dennyzhang.com/swap-two-integers-in-array
// Basic Ideas:
// Complexity: Time O(1), Space O(1)
/**
 * @param A: An integer array
 * @param index1: the first index
 * @param index2: the second index
 * @return: nothing
 */
func swapIntegers (A *[]int, index1 int, index2 int)  {
    if index1<0 || index1>=len(*A) || index2<0 || index2>=len(*A) { return }
    (*A)[index1], (*A)[index2] = (*A)[index2], (*A)[index1]
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.