面試10大演算法題匯總-字串和數組7,演算法數組

來源:互聯網
上載者:User

面試10大演算法題匯總-字串和數組7,演算法數組

14.實現strStr():搜尋一個字串在另一個字串中的第一次出現的位置

例:

#include <stdio.h>#include <string.h>int main (){  char str[] ="This is a simple string";  char * pch;  pch = strstr (str,"simple");  cout<<(*pch)<<endl;  return 0;}

輸出:s

這裡主要要考慮一下特殊情況。

Code:

public class test {public static String strStr(String origin, String needle) {int originLen = origin.length();int needleLen = needle.length();if (needleLen == originLen && originLen == 0)return "";if (needleLen == 0)return origin;for (int i = 0; i < originLen; ++i) {if (originLen - i + 1 < needleLen)return null;int k = i;int j = 0;while (j < needleLen && k < originLen&& needle.charAt(j) == origin.charAt(i)) {++j;++k;if (j == needleLen)return origin.substring(i);}}return null;}public static void main(String[] args) {int[] a = { 2, 7, 11, 23 };}}

16.尋找插入位置:給定一個有序數組和一個目標值,若該值在數組中存在,則返回其index,否則返回其應該插入的位置。

例:

[1,3,5,6], 5 -> 2

[1,3,5,6], 2 -> 1

[1,3,5,6], 7 -> 4

[1,3,5,6], 0 -> 0

解法一:遍曆

Code:

public class test {public static int arrPos(int[] A, int target) {if (A == null)return 0;if (target <= A[0])return 0;for (int i = 0; i < A.length - 1; i++) {if (target > A[i] && target <= A[i + 1]) {return i + 1;}}return A.length;}public static void main(String[] args) {int[] a = { 2, 7, 11, 23 };System.out.println(arrPos(a, 223));}}

解法二:二分尋找

Code:

public class test {public static int arrPos(int[] A, int target) {if (A == null || A.length == 0)return 0;return searchInsert(A, target, 0, A.length - 1);}public static int searchInsert(int[] A, int target, int start, int end) {int mid = (start + end) / 2;if (target == A[mid])return mid;else if (target < A[mid])return start < mid ? searchInsert(A, target, start, mid - 1): start;elsereturn end > mid ? searchInsert(A, target, mid + 1, end): (end + 1);}public static void main(String[] args) {int[] a = { 2, 7, 11, 23 };System.out.println(arrPos(a, 223));}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.