Magic indexes

In array A[0…n-1], there is A so-called magic index that satisfies the condition A[I] = I. Given an ordered array of integers, write A method to find the magic index, if any, in array A. If none, return -1. If there are more than one magic index, return the smallest index value.

Example 1:

Input: nums = [0, 2, 3, 4, 5] Output: 0 Description: 0 subscript elements are 0 example 2:

Input: nums = [1, 1, 1]

The nums length is between [1, 1000000]. This title is follow-up in the original book, i.e. the version of the array that may contain repeating elements

On the first code

java

class Solution {

    public int findMagicIndex(int[] nums) {

for(int i = 0; i<nums.length; i++){

            if(nums[i] == i){

                return i;

            }

        }

        return -1;

    }

}

python

class Solution(object):

    def findMagicIndex(self, nums):

        for i in range(len(nums)):

            if nums[i] == i:

                return i

        return -1

Title looking at a long actually very simple, the first loop iterate through group, the need to get the length of the array, before getting a location corresponding to the value of the compared with the number of the location, the same is direct return to the location of the index value, different words continue to the next, if you are not in conformity with the provisions has been to the end of the cycle return – 1, What if I don’t have to have multiple of them, because in that case the first one is the most important one.

The sum of two Numbers

Given an array of integers nums and a target value target, find the two integers in the array and the target values and return their array subscripts.

You can assume that there is only one answer for each type of input. However, the same element in an array cannot be used twice.

 

Example:

Given nums = [2, 7, 11, 15], target = 9

Nums [0] + nums[1] = 2 + 7 = 9

java

class Solution {

    public int[] twoSum(int[] nums, int target) {

        for (int i = 0; i < nums.length – 1; i++) {

            for (int j = i + 1; j < nums.length; j++)

                if (nums[i] + nums[j] == target)

                    return new int[]{i, j};

        }

        return new int[]{-1, -1};

    }

}

python

class Solution(object):

    def twoSum(self, nums, target):

        res=[]

        for i in range(len(nums)):

            for j in range(len(nums)):

if i ! = j:

                    if (nums[i]+nums[j]) == target:

                        res.append(i)

                        res.append(j)

                        return res

If not, continue to add the second value to all the other values until you find the compound number, then save the index value to the RES array, and return.