两个数组的内容是否相同

// 两个数组的内容是否相同 a.equals(b);
if (Array.prototype.equals)
console.warn(“Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there’s a framework conflict or you’ve got double inclusions in your code.”);
// attach the .equals method to Array’s prototype to call it on any array
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;

// compare lengths - can save a lot of time 
if (this.length != array.length)
    return false;

for (var i = 0, l = this.length; i < l; i++) {
    // Check if we have nested arrays
    if (this[i] instanceof Array && array[i] instanceof Array) {
        // recurse into the nested arrays
        if (!this[i].equals(array[i]))
            return false;
    }
    else if (this[i] !== array[i]) {
        // Warning - two different object instances will never be equal: {x:20} != {x:20}
        return false;
    }
}
return true;

}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, “equals”, { enumerable: false });

在C语言中,判断两个数组内容是否相同,常见有以下几种方法: ### 方法一:简单遍历比较法 通过两层嵌套循环,对两个数组的每个元素进行逐一比较。如果在比较过程中发现有元素不相等,则判定两个数组内容不同;若所有元素都相等,则判定两个数组内容相同。 ```c #include <stdio.h> int main() { int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {1, 2, 3, 4, 5}; int i, j; int isSame = 1; if (sizeof(arr1) != sizeof(arr2)) { isSame = 0; } else { for (i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i++) { if (arr1[i] != arr2[i]) { isSame = 0; break; } } } if (isSame) { printf("两个数组内容相同\n"); } else { printf("两个数组内容不同\n"); } return 0; } ``` ### 方法二:先排序再比较法 先对两个数组进行排序,再依次比较对应位置的元素。若排序后所有对应位置的元素都相等,则两个数组内容相同;反之则不同。下面示例使用快速排序对数组进行排序: ```c #include <stdio.h> // 快速排序 void stor(int a[], int left, int right) { int i = left; int j = right; int temp = a[left]; if (right < left) { return; } while (i != j) { while (a[j] >= temp && j > i) { j--; } if (j > i) { a[i] = a[j]; i++; } while (a[i] <= temp && j > i) { i++; } if (j > i) { a[j] = a[i]; j--; } } a[i] = temp; stor(a, left, i - 1); stor(a, i + 1, right); } int same_set(int a[], int b[], int len) { int s = 1; for (int i = 0; i < len; i++) { if (a[i] != b[i]) { s = 0; break; } } return s; } int main() { int a[200] = {0}; int b[200] = {0}; int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } for (int i = 0; i < n; i++) { scanf("%d", &b[i]); } stor(a, 0, n - 1); stor(b, 0, n - 1); int t = same_set(a, b, n); if (t) { printf("两个数组内容相同\n"); } else { printf("两个数组内容不同\n"); } return 0; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值