数组基础问题

1.Sum of the array numbers

int sum(int[] nums) {
    int result = 0;
    for (int i = 0; i < nums.length; i++) {
        result += nums[i];
    }
    return result;
}

2.Minimum element of the array

int minimum(int a , int b) {
    if (a < b) {
        return a;
    }
    return b;
}

int minimum(int[] nums) {
    int min = Integer.MAX_VALUE;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] < min) {
            min = nums[i];
        }
    }
    return min;
}

3.Second minimum element of the array

int secondMinimum(int[] nums) {
    int min = Math.min(nums[0],nums[1]);
    int secondMin = Math.max(nums[0],nums[1]);
    for (int i = 2; i < nums.length; i++) {
        if (nums[i] < min) {
            secondMin = min;
            min = nums[i];
        } else if (nums[i] == min) {
            secondMin = min;
        } else if (nums[i] > min && nums[i] < secondMin) {
            secondMin = nums[i];
        } else if (nums[i] == secondMin) {
            continue;
        } else {
            continue;
        }
    }
    return secondMin;
}

4.Reverse Array

//双指针,前后交换
public void reverseArray(int[] nums) {
    int first = 0, end = nums.length - 1;
    while (first < end) {
        swap(nums,first++,end--);
    }
}
private void swap(int[] nums, int first, int second) {
    //注意这里的first和second和上面的区别,不同的函数
    int temp = nums[first];
    nums[first] = nums[second];
    nums[second] = temp;
}

5.Odd Even Sort
奇数在前,偶数在后

public void oddEvenSort(int[] nums) {
    int first = 0, second = nums.length-1;
    while (first < second) {
        while (first < second && nums[fisrt] % 2 == 1) {
            first++;//如果是奇数就跳过继续往下遍历&每次都判断first < second防止越界
        }
        while (first < second && nums[second] % 2 == 0) {
            second--;
        }
        if (first < second) {
            swap(nums,first++,second--);
        }
    }
}

6.Pivot Sort
找出一个数,左边的数都比他小,右边的都比他大


public void pivotSort(int[] nums, int pivot) {
    int first = 0, second = nums.length - 1;
    while (first < second && nums[first] <= pivot) {
        first++;
    }
    while (first < second && nums[second] > pivot) {
        second--;
    }
    if (first < second) {
        swap(nums,first++,second--);
    }
}
public void swap(int[] nums, int i, int j) {
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

7.Remove Element
前后指针,把要删除的元素放在最后。first指针从左边开始数,不相等就跳过,相等就和右边不等于目标值的元素交换

public int removeElement(int[] nums, int val) {
    if (nums.length == 0) {
        return 0;
    }
    int first = 0, second = nums.length - 1;
    while (first < second) {
        while (first < second && nums[first] != val) {
            first++;
        }
        while (first < second && nums[second] == val) {
            //等于目标值就放在最后
            second--;
        }
        if (first < second) {
            swap(nums,first++,second--);
        }
    }
    return return nums[first] != val ? first+1 : first;//例子[3,2,2,3]删掉3,考虑first等于second
}
//Solution2 for remvoe element
public int removeElement(int[] nums, int val) {
    int index = 0, len = nums.length;
    //len is the valid length of remaining array
    while (index < len) {
        if (nums[index] == val) {
            len--;//remove one element
            //Keep the possible valid element
            nums[index] = nums[len];
        } else {
            index++;
        }
    }
    return len;
}

8.Merge Two Sorted Array

//粗暴的做法,两个数组,两个指针分别指向数组的头地址,小的放入新的数组里,然后最后再把result的数压到nums1里。需要额外空间。这道题注意是把nums2压入nums1,而不是生成一个新的数组
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int[] result = new int[m + n];
        int i = 0, j = 0, index = 0;
        while (i < m && j < n) {
            if (nums1[i] < nums2[j]) {
                result[index++] = nums1[i++];
            } else {
                result[index++] = nums2[j++];
            }
        }
        while (i < m) {
            result[index++] = nums1[i++];
        }
        while (j < n) {
            result[index++] = nums2[j++];   
        }
        for (i = 0; i < m + n; i++) {
            nums1[i] = result[i];
        }
        
    }
}

solution:归并排序,分而治之

class Solution:
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        result = []
        left, right = 0, 0
        while left < m and right < n:
            if nums1[left] < nums2[right]:
                result.append(nums1[left])
                left += 1
            else:
                result.append(nums2[right])
                right += 1
         #比较完以后肯定有一个数组没有出完       
        while left < m:
            result.append(nums1[left])
            left += 1
        
        while right < n:
            result.append(nums2[right])
            right += 1
            
        for i in range(m + n):
            nums1[i] = result[i]
            
引申:[Sort Integer II]http://www lintcode.com/en/problem/sort-integers-ii/

solution:归并排序,注意这里是在原来数组基础上生成了buffer,而不是生成新的数组,注意区别

class Solution:
    """
    @param A: an integer array
    @return: nothing
    """
    def sortIntegers2(self, A):
        # write your code here
         m = len(A)
         temp = [0 for _ in range(m)]
         self.mergeSort(A, 0, m - 1, temp)
         
    def mergeSort(self, A, start, end, temp):
        if start >= end:
            return 
        
        mid = (start + end) / 2
        #递归,分区间
        self.mergeSort(A, start, mid, temp)
        self.mergeSort(A, mid + 1, end, temp)
        #递归完了以后最后要合并两个"数组",这里就是两个区间
        self.merge(A, start, end, temp)
        
    def merge(self, A, start, end, temp):
        mid = (start + end) / 2
        
        left, right = start, mid + 1
        # temp buffer已经有了,不能直接append,进行合并一个大区间(不是生成新的数组)
        index = start
        while left <= mid and right <= end:
            
            if A[left] < A[right]:
                temp[index] = A[left]
                left += 1
                index += 1
            else:
                temp[index] = A[right]
                right += 1
                index += 1
        
        while left <= mid:
            temp[index] = A[left]
            left += 1
            index += 1
            
        while right <= end:
            temp[index] = A[right]
            right += 1
            index += 1
            
        for index in range(start, end + 1):
            A[index] = temp[index]

solution2: 快排,比归并排序空间复杂度更低,不需要额外的数组,注意pivot的选取

class Solution:
    # @param {int[]} A an integer array
    # @return nothing
    def sortIntegers2(self, A):
        # Write your code here
        self.quickSort(A, 0, len(A) - 1)
    
    def quickSort(self, A, start, end):
        if start >= end:
            return
        
        left, right = start, end
        # key point 1: pivot is the value, not the index
        pivot = A[(start + end) / 2]

        # key point 2: every time you compare left & right, it should be 
        # left <= right not left < right
        while left <= right:
            while left <= right and A[left] < pivot:
                left += 1
            
            while left <= right and A[right] > pivot:
                right -= 1
            
            if left <= right:
                A[left], A[right] = A[right], A[left]
                
                left += 1
                right -= 1
        
        self.quickSort(A, start, right)
        self.quickSort(A, left, end)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容