leetcode-classic interview/written test questions

1. Disappearing numbers

Interview question 17.04. Missing number - LeetCodeicon-default.png?t=N7T8https://leetcode.cn/problems/missing-number-lcci/

Of course there are several solutions to this question. Here I recommend a better idea, which isThe single dog idea: XOR .

The characteristic of XOR is that the difference is 1 and the same number is 0, that is, the XOR of two identical numbers is equal to 0.

Then we only need to use two loops to solve the problem.

The first loop traverses all the elements of the nums array. Since there is one missing element, 5, the judgment condition is i<numsSize. Assume that the elements in the array are as follows, then the second loop only needs to fill in the missing number. , the judgment condition is i<=numsSize, and then tail and i are XORed.

Then we can understand that tail is traversing two arrays at the same time. A little knowledge everyone needs to know here is that the final result of 3^4^3^4 is still 0. Because the commutative law can be used here, that is, 3^3^4^4, which is equivalent to the final XOR of two 0s, which is still 0. Except for the disappeared number that appears once, the other numbers appear in pairs, so the tail result after two XOR traversals is the disappeared number.

int missingNumber(int* nums, int numsSize)
{
   int tail=0,i;
   for(i=0;i<numsSize;i++)
   {
       tail^=nums[i];
   }
   for(i=0;i<=numsSize;i++)
   {
       tail^=i;
   }
   return tail;
}

 2. Rotate array

189. Rotate array - LeetCodeicon-default.png?t=N7T8https://leetcode.cn/problems/rotate-array/description/Here I also provide a better idea. We need to invert this array three times. The first inversion is numsSize-1-k elements. Because numsSize is the number of elements, the inverted position is the subscript, so It requires -1, k pieces after the second reversal, and the third reversal is the overall reversal. This method is very difficult to think of, but it is very efficient.

void Func(int* nums,int left,int right)
{
    while(left<=right)
    {
        int tmp=nums[left];
        nums[left]=nums[right];
        nums[right]=tmp;
        left++;
        right--;
    }
}
void rotate(int* nums, int numsSize, int k)
{
   if(k>=numsSize)
   {
       k=k%numsSize;
   }
   //第一次逆置前numsSize-k个
   Func(nums,0,numsSize-k-1);
   //第二次逆置后k个
   Func(nums,numsSize-k,numsSize-1);
   //第三次将整个数组逆置
   Func(nums,0,numsSize-1);
}

おすすめ

転載: blog.csdn.net/2301_79035870/article/details/134231924